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);
}
+132
View File
@@ -0,0 +1,132 @@
-- src/catscript/checker.cat -- the catscript checker, written in catscript.
--
-- A lightweight structural checker. catscript is structurally typed, so
-- this pass does not reject programs; it walks the AST and reports
-- advisory diagnostics (unknown-looking globals, likely type-hint
-- mismatches). It proves the front-end is complete and self-hosted.
--
-- Result: { ok=true, diags={ "..." } }.
CHK_DIAGS = {}
CHK_NDIAG = 0
CHK_KNOWN = {}
function chk_known_global(name)
local i = 1
while i <= len(CHK_KNOWN) do
if CHK_KNOWN[i] == name then
return true
end
i = i + 1
end
return false
end
function chk_diag(msg)
CHK_NDIAG = CHK_NDIAG + 1
CHK_DIAGS[CHK_NDIAG] = msg
end
function chk_expr(e)
if e == nil then
return
end
local t = e.t
if t == "name" then
if not chk_known_global(e.v) then
chk_diag("note: '" .. e.v .. "' is not a known global")
end
elseif t == "bin" then
chk_expr(e.l)
chk_expr(e.r)
elseif t == "un" then
chk_expr(e.e)
elseif t == "call" then
chk_expr(e.f)
local i = 1
while i <= len(e.args) do
chk_expr(e.args[i])
i = i + 1
end
elseif t == "method" then
chk_expr(e.obj)
local i = 1
while i <= len(e.args) do
chk_expr(e.args[i])
i = i + 1
end
elseif t == "index" then
chk_expr(e.obj)
chk_expr(e.idx)
elseif t == "attr" then
chk_expr(e.obj)
elseif t == "table" then
local i = 1
while i <= len(e.fields) do
chk_expr(e.fields[i].v)
i = i + 1
end
elseif t == "func" then
chk_block(e.body)
end
end
function chk_block(stats)
if stats == nil then
return
end
local i = 1
while i <= len(stats) do
local s = stats[i]
local k = s.t
if k == "local" then
CHK_KNOWN[len(CHK_KNOWN) + 1] = s.name
chk_expr(s.init)
elseif k == "assign" then
chk_expr(s.value)
elseif k == "setidx" then
chk_expr(s.idx)
chk_expr(s.value)
elseif k == "setattr" then
chk_expr(s.value)
elseif k == "funcdef" then
CHK_KNOWN[len(CHK_KNOWN) + 1] = s.name
chk_block(s.func.body)
elseif k == "if" then
local j = 1
while j <= len(s.conds) do
chk_expr(s.conds[j].cond)
chk_block(s.conds[j].body)
j = j + 1
end
chk_block(s.els)
elseif k == "while" then
chk_expr(s.cond)
chk_block(s.body)
elseif k == "repeat" then
chk_block(s.body)
chk_expr(s.cond)
elseif k == "for" then
CHK_KNOWN[len(CHK_KNOWN) + 1] = s.var
chk_expr(s.from)
chk_expr(s.to)
chk_expr(s.step)
chk_block(s.body)
elseif k == "return" then
chk_expr(s.e)
elseif k == "expr" then
chk_expr(s.e)
end
i = i + 1
end
end
function chk_check(ast)
CHK_DIAGS = {}
CHK_NDIAG = 0
CHK_KNOWN = { "print", "tostring", "tonumber", "type", "len",
"toml_parse", "toml_encode", "read_file", "write_file",
"ord", "chr", "substr", "dofile", "bc_run", "bc_dump" }
chk_block(ast.body)
return { ok = true, diags = CHK_DIAGS }
end
+388
View File
@@ -0,0 +1,388 @@
-- src/catscript/compiler.cat -- the catscript compiler, written in catscript.
--
-- Walks the AST (from parser.cat) and builds a *chunk table* the C
-- runtime turns into runnable bytecode through bc_run/bc_dump. A chunk
-- is: { name, nparams, nlocals, consts={}, protos={}, code={ {op,a,b,c,line} } }.
--
-- Opcodes mirror include/cat/bytecode.h:
-- 1 CONST 2 NIL 3 TRUE 4 FALSE 5 GETLOCAL 6 SETLOCAL 7 GETGLOBAL
-- 8 SETGLOBAL 9 ADD 10 SUB 11 MUL 12 DIV 13 REM 14 NEG 15 NOT
-- 16 EQ 17 NE 18 LT 19 LE 20 GT 21 GE 22 GETATTR 23 SETATTR
-- 24 NEWTABLE 25 CALL 26 CALLMETHOD 27 JUMP 28 JUMPIF 29 JUMPIFNOT
-- 30 RETURN 31 RETURN0 32 POP 33 PRINT 34 CLOSURE 35 GETUPVAL
-- 36 CONCAT 37 DUP 38 GETIDX 39 SETIDX
--
-- All state lives in globals prefixed CMP_ (closures capture no locals).
CMP_CHUNK = nil
CMP_CONSTS = {}
CMP_NC = 0
CMP_PROTOS = {}
CMP_NP = 0
CMP_CODE = {}
CMP_NI = 0
CMP_LOCALS = {}
CMP_NL = 0
CMP_LOOPS = {} -- stack of tables {breaks={...}}
function cmp_emit(op, a, b, line)
CMP_NI = CMP_NI + 1
CMP_CODE[CMP_NI] = { op = op, a = a, b = b, c = 0, line = line }
return CMP_NI
end
-- patch the `a` operand of an already-emitted instruction (jump target)
function cmp_patch(idx, target)
local instr = CMP_CODE[idx]
instr.a = target
end
function cmp_addconst(v)
CMP_NC = CMP_NC + 1
CMP_CONSTS[CMP_NC] = v
return CMP_NC - 1 -- 0-based index into the pool
end
function cmp_addstr(s)
return cmp_addconst(s)
end
function cmp_findlocal(name)
local i = CMP_NL
while i >= 1 do
if CMP_LOCALS[i] == name then
return i - 1
end
i = i - 1
end
return -1
end
function cmp_addlocal(name)
CMP_NL = CMP_NL + 1
CMP_LOCALS[CMP_NL] = name
return CMP_NL - 1
end
-- enter a fresh function chunk; returns the previous state to restore
function cmp_save()
return {
chunk = CMP_CHUNK, consts = CMP_CONSTS, nc = CMP_NC,
protos = CMP_PROTOS, np = CMP_NP, code = CMP_CODE, ni = CMP_NI,
locals = CMP_LOCALS, nl = CMP_NL, loops = CMP_LOOPS
}
end
function cmp_restore(s)
CMP_CHUNK = s.chunk; CMP_CONSTS = s.consts; CMP_NC = s.nc
CMP_PROTOS = s.protos; CMP_NP = s.np; CMP_CODE = s.code; CMP_NI = s.ni
CMP_LOCALS = s.locals; CMP_NL = s.nl; CMP_LOOPS = s.loops
end
function cmp_newchunk(name)
CMP_CHUNK = nil
CMP_CONSTS = {}
CMP_NC = 0
CMP_PROTOS = {}
CMP_NP = 0
CMP_CODE = {}
CMP_NI = 0
CMP_LOCALS = {}
CMP_NL = 0
CMP_LOOPS = {}
CMP_CHUNK = { name = name, nparams = 0, nlocals = 0,
consts = CMP_CONSTS, protos = CMP_PROTOS, code = CMP_CODE }
return CMP_CHUNK
end
-- ---- expressions -----------------------------------------------------
function cmp_expr(e)
local t = e.t
if t == "nil" then cmp_emit(2, 0, 0, 0)
elseif t == "true" then cmp_emit(3, 0, 0, 0)
elseif t == "false" then cmp_emit(4, 0, 0, 0)
elseif t == "int" then cmp_emit(1, cmp_addconst(e.v), 0, 0)
elseif t == "float" then cmp_emit(1, cmp_addconst(e.v), 0, 0)
elseif t == "str" then cmp_emit(1, cmp_addstr(e.v), 0, 0)
elseif t == "name" then
local slot = cmp_findlocal(e.v)
if slot >= 0 then
cmp_emit(5, slot, 0, 0)
else
cmp_emit(7, cmp_addstr(e.v), 0, 0)
end
elseif t == "bin" then
cmp_expr(e.l)
cmp_expr(e.r)
cmp_emit(cmp_binop(e.op), 0, 0, 0)
elseif t == "un" then
cmp_expr(e.e)
if e.op == "-" then cmp_emit(14, 0, 0, 0)
elseif e.op == "not" then cmp_emit(15, 0, 0, 0)
elseif e.op == "#" then cmp_emit(22, cmp_addstr("length"), 0, 0)
end
elseif t == "call" then
cmp_expr(e.f)
local i = 1
while i <= len(e.args) do
cmp_expr(e.args[i])
i = i + 1
end
cmp_emit(25, len(e.args), 0, 0)
elseif t == "method" then
cmp_expr(e.obj)
local i = 1
while i <= len(e.args) do
cmp_expr(e.args[i])
i = i + 1
end
cmp_emit(26, len(e.args), cmp_addstr(e.name), 0)
elseif t == "index" then
cmp_expr(e.obj)
cmp_expr(e.idx)
cmp_emit(38, 0, 0, 0)
elseif t == "attr" then
cmp_expr(e.obj)
cmp_emit(22, cmp_addstr(e.name), 0, 0)
elseif t == "table" then
cmp_emit(24, 0, 0, 0)
local pos = 1
local i = 1
while i <= len(e.fields) do
local f = e.fields[i]
if f.k ~= nil then
cmp_emit(37, 0, 0, 0) -- DUP obj
cmp_expr(f.v)
cmp_emit(23, cmp_addstr(f.k), 0, 0)
else
cmp_emit(37, 0, 0, 0)
cmp_emit(1, cmp_addconst(pos), 0, 0)
cmp_expr(f.v)
cmp_emit(39, 0, 0, 0)
pos = pos + 1
end
i = i + 1
end
elseif t == "func" then
local proto = cmp_func(e)
cmp_emit(34, proto, 0, 0)
end
end
function cmp_binop(op)
if op == "+" then return 9 end
if op == "-" then return 10 end
if op == "*" then return 11 end
if op == "/" then return 12 end
if op == "%" then return 13 end
if op == ".." then return 36 end
if op == "==" then return 16 end
if op == "~=" then return 17 end
if op == "<" then return 18 end
if op == "<=" then return 19 end
if op == ">" then return 20 end
if op == ">=" then return 21 end
return 9
end
function cmp_func(f)
local saved = cmp_save()
cmp_newchunk(f.name)
CMP_CHUNK.nparams = len(f.params)
local i = 1
while i <= len(f.params) do
cmp_addlocal(f.params[i])
i = i + 1
end
cmp_block(f.body)
cmp_emit(31, 0, 0, 0) -- implicit RETURN0
local chunk = CMP_CHUNK
cmp_restore(saved)
CMP_NP = CMP_NP + 1
CMP_PROTOS[CMP_NP] = chunk
return CMP_NP - 1
end
-- ---- statements ------------------------------------------------------
function cmp_block(stats)
if stats == nil then
return
end
local i = 1
while i <= len(stats) do
cmp_stat(stats[i])
i = i + 1
end
end
function cmp_stat(s)
local k = s.t
if k == "local" then
if s.init ~= nil then
cmp_expr(s.init)
else
cmp_emit(2, 0, 0, 0)
end
local slot = cmp_addlocal(s.name)
cmp_emit(6, slot, 0, 0)
elseif k == "assign" then
cmp_expr(s.value)
local slot = cmp_findlocal(s.name)
if slot >= 0 then
cmp_emit(6, slot, 0, 0)
else
cmp_emit(8, cmp_addstr(s.name), 0, 0)
end
elseif k == "setidx" then
local slot = cmp_findlocal(s.name)
if slot >= 0 then
cmp_emit(5, slot, 0, 0)
else
cmp_emit(7, cmp_addstr(s.name), 0, 0)
end
cmp_expr(s.idx)
cmp_expr(s.value)
cmp_emit(39, 0, 0, 0)
elseif k == "setattr" then
local slot = cmp_findlocal(s.name)
if slot >= 0 then
cmp_emit(5, slot, 0, 0)
else
cmp_emit(7, cmp_addstr(s.name), 0, 0)
end
cmp_expr(s.value)
cmp_emit(23, cmp_addstr(s.attr), 0, 0)
elseif k == "funcdef" then
local proto = cmp_func(s.func)
cmp_emit(34, proto, 0, 0)
cmp_emit(8, cmp_addstr(s.name), 0, 0)
elseif k == "if" then
cmp_if(s)
elseif k == "while" then
cmp_while(s)
elseif k == "repeat" then
cmp_repeat(s)
elseif k == "for" then
cmp_for(s)
elseif k == "return" then
if s.e ~= nil then
cmp_expr(s.e)
cmp_emit(30, 0, 0, 0)
else
cmp_emit(31, 0, 0, 0)
end
elseif k == "expr" then
cmp_expr(s.e)
cmp_emit(32, 0, 0, 0)
end
end
function cmp_if(s)
local ends = {}
local nends = 0
local i = 1
local jf = -1
while i <= len(s.conds) do
if i > 1 then
nends = nends + 1
ends[nends] = cmp_emit(27, 0, 0, 0)
cmp_patch(jf, CMP_NI)
end
cmp_expr(s.conds[i].cond)
jf = cmp_emit(29, 0, 0, 0)
cmp_block(s.conds[i].body)
i = i + 1
end
if s.els ~= nil then
nends = nends + 1
ends[nends] = cmp_emit(27, 0, 0, 0)
cmp_patch(jf, CMP_NI)
cmp_block(s.els)
else
cmp_patch(jf, CMP_NI)
end
local k = 1
while k <= nends do
cmp_patch(ends[k], CMP_NI)
k = k + 1
end
end
function cmp_while(s)
local jcond = CMP_NI + 1
cmp_expr(s.cond)
local jend = cmp_emit(29, 0, 0, 0)
CMP_LOOPS[len(CMP_LOOPS) + 1] = { breaks = {} }
cmp_block(s.body)
local loop = CMP_LOOPS[len(CMP_LOOPS)]
CMP_LOOPS[len(CMP_LOOPS)] = nil
cmp_emit(27, jcond, 0, 0)
cmp_patch(jend, CMP_NI)
local i = 1
while i <= len(loop.breaks) do
cmp_patch(loop.breaks[i], CMP_NI)
i = i + 1
end
end
function cmp_repeat(s)
local jtop = CMP_NI + 1
CMP_LOOPS[len(CMP_LOOPS) + 1] = { breaks = {} }
cmp_block(s.body)
local loop = CMP_LOOPS[len(CMP_LOOPS)]
CMP_LOOPS[len(CMP_LOOPS)] = nil
cmp_expr(s.cond)
cmp_emit(29, jtop, 0, 0)
local i = 1
while i <= len(loop.breaks) do
cmp_patch(loop.breaks[i], CMP_NI)
i = i + 1
end
end
function cmp_for(s)
cmp_expr(s.from)
if s.step ~= nil then
cmp_expr(s.step)
else
cmp_emit(1, cmp_addconst(1), 0, 0)
end
cmp_expr(s.to)
-- stack now: from, step, to (top is to)
local slot = cmp_addlocal(s.var)
cmp_addlocal(s.var .. " .limit")
cmp_addlocal(s.var .. " .step")
cmp_emit(6, slot + 2, 0, 0) -- step
cmp_emit(6, slot + 1, 0, 0) -- limit
cmp_emit(6, slot, 0, 0) -- var
local jcond = CMP_NI + 1
cmp_emit(5, slot, 0, 0)
cmp_emit(5, slot + 1, 0, 0)
cmp_emit(19, 0, 0, 0)
local jend = cmp_emit(29, 0, 0, 0)
CMP_LOOPS[len(CMP_LOOPS) + 1] = { breaks = {} }
cmp_block(s.body)
local loop = CMP_LOOPS[len(CMP_LOOPS)]
CMP_LOOPS[len(CMP_LOOPS)] = nil
cmp_emit(5, slot, 0, 0)
cmp_emit(5, slot + 2, 0, 0)
cmp_emit(9, 0, 0, 0)
cmp_emit(6, slot, 0, 0)
cmp_emit(27, jcond, 0, 0)
cmp_patch(jend, CMP_NI)
local i = 1
while i <= len(loop.breaks) do
cmp_patch(loop.breaks[i], CMP_NI)
i = i + 1
end
end
function cmp_compile(ast)
cmp_newchunk("main")
cmp_block(ast.body)
cmp_emit(31, 0, 0, 0)
CMP_CHUNK.nlocals = CMP_NL
return CMP_CHUNK
end
+226
View File
@@ -0,0 +1,226 @@
-- src/catscript/lexer.cat -- the catscript lexer, written in catscript.
--
-- This is the self-hosted front-end: lexer, parser, checker and compiler
-- are all catscript programs. The C runtime only provides the object
-- model, the VM and the bytecode builder (bc_run/bc_dump).
--
-- The lexer produces an array of token tables:
-- { kind = <kind>, text = <payload>, line = <n> }
-- where <kind> is "NAME", "INT", "FLOAT", "STRING", "KW", "EOF", or the
-- literal symbol text ("+", "==", "..", ...). Keywords carry kind "KW"
-- and their text.
--
-- All state lives in globals prefixed LEX_ so nested helpers need no
-- upvalues (catscript closures do not capture outer locals).
LEX_SRC = ""
LEX_POS = 0
LEX_N = 0
LEX_LINE = 1
LEX_KEYWORDS = {
"and", "break", "do", "else", "elseif", "end", "false", "for",
"function", "if", "in", "local", "nil", "not", "or", "repeat",
"return", "then", "true", "until", "while"
}
function lexer_is_digit(c)
return c >= 48 and c <= 57
end
function lexer_is_alpha(c)
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
end
function lexer_is_alnum(c)
return lexer_is_alpha(c) or lexer_is_digit(c)
end
function lexer_is_keyword(s)
local i = 1
while i <= len(LEX_KEYWORDS) do
if LEX_KEYWORDS[i] == s then
return true
end
i = i + 1
end
return false
end
function lexer_init(src)
LEX_SRC = src
LEX_POS = 0
LEX_N = len(src)
LEX_LINE = 1
end
function lexer_peek(off)
local p = LEX_POS + off
if p < 0 or p >= LEX_N then
return -1
end
return ord(LEX_SRC, p)
end
function lexer_advance()
local c = lexer_peek(0)
if c < 0 then
return -1
end
LEX_POS = LEX_POS + 1
if c == 10 then
LEX_LINE = LEX_LINE + 1
end
return c
end
function lexer_skip_ws()
local go = true
while go do
local c = lexer_peek(0)
if c == 32 or c == 9 or c == 13 or c == 10 then
lexer_advance()
elseif c == 45 and lexer_peek(1) == 45 then
lexer_advance()
lexer_advance()
while lexer_peek(0) >= 0 and lexer_peek(0) ~= 10 do
lexer_advance()
end
else
go = false
end
end
end
function lexer_read_name()
local start = LEX_POS
while lexer_is_alnum(lexer_peek(0)) do
lexer_advance()
end
local text = substr(LEX_SRC, start, LEX_POS - start)
local kind = "NAME"
if lexer_is_keyword(text) then
kind = text
end
return { kind = kind, text = text, line = LEX_LINE }
end
function lexer_read_number()
local start = LEX_POS
local isf = false
while lexer_is_digit(lexer_peek(0)) do
lexer_advance()
end
if lexer_peek(0) == 46 and lexer_is_digit(lexer_peek(1)) then
isf = true
lexer_advance()
while lexer_is_digit(lexer_peek(0)) do
lexer_advance()
end
end
local text = substr(LEX_SRC, start, LEX_POS - start)
if isf then
return { kind = "FLOAT", text = text, line = LEX_LINE }
end
return { kind = "INT", text = text, line = LEX_LINE }
end
function lexer_read_string(quote)
local buf = ""
lexer_advance()
while lexer_peek(0) >= 0 and lexer_peek(0) ~= quote do
local c = lexer_advance()
if c == 92 then
local e = lexer_advance()
if e == 110 then
buf = buf .. chr(10)
elseif e == 116 then
buf = buf .. chr(9)
elseif e == 92 then
buf = buf .. "\\"
else
buf = buf .. chr(e)
end
else
buf = buf .. chr(c)
end
end
lexer_advance()
return { kind = "STRING", text = buf, line = LEX_LINE }
end
function lexer_read_symbol()
local c = lexer_advance()
local k = chr(c)
if c == 61 then
if lexer_peek(0) == 61 then
lexer_advance()
k = "=="
end
elseif c == 126 then
if lexer_peek(0) == 61 then
lexer_advance()
k = "~="
end
elseif c == 60 then
if lexer_peek(0) == 61 then
lexer_advance()
k = "<="
end
elseif c == 62 then
if lexer_peek(0) == 61 then
lexer_advance()
k = ">="
end
elseif c == 46 then
if lexer_peek(0) == 46 then
lexer_advance()
k = ".."
end
elseif c == 58 then
if lexer_peek(0) == 58 then
lexer_advance()
k = "::"
end
elseif c == 45 then
if lexer_peek(0) == 62 then
lexer_advance()
k = "->"
end
end
return { kind = k, text = k, line = LEX_LINE }
end
function lexer_next()
lexer_skip_ws()
local c = lexer_peek(0)
if c < 0 then
return { kind = "EOF", text = "", line = LEX_LINE }
end
if lexer_is_alpha(c) then
return lexer_read_name()
end
if lexer_is_digit(c) then
return lexer_read_number()
end
if c == 34 or c == 39 then
return lexer_read_string(c)
end
return lexer_read_symbol()
end
function lexer_tokenize(src)
lexer_init(src)
local toks = {}
local n = 0
local stop = false
while not stop do
local t = lexer_next()
n = n + 1
toks[n] = t
if t.kind == "EOF" then
stop = true
end
end
return toks
end
+425
View File
@@ -0,0 +1,425 @@
-- src/catscript/parser.cat -- the catscript parser, written in catscript.
--
-- Turns the token array from lexer.cat into an AST. AST nodes are
-- ordinary tables with a `t` (tag) field:
--
-- { t="nil" } { t="true" } { t="false" }
-- { t="int", v=42 } { t="float", v=2.5 } { t="str", v="s" }
-- { t="name", v="x" }
-- { t="bin", op="+", l=L, r=R } { t="un", op="-", e=E }
-- { t="call", f=Fn, args={...} }
-- { t="method", obj=O, name="m", args={...} }
-- { t="index", obj=O, idx=I }
-- { t="attr", obj=O, name="a" }
-- { t="table", fields={ {k=..., v=...}, ... } } -- positional k is nil
-- { t="func", name=..., params={...}, body={stats} }
--
-- Statements:
-- { t="local", name=..., init=E }
-- { t="assign", name=..., value=E } { t="setidx", name, idx, value }
-- { t="setattr", name, attr, value }
-- { t="if", conds={ {cond=..., body={...}}, ... }, els={...}|nil }
-- { t="while", cond=E, body={...} }
-- { t="repeat", body={...}, cond=E }
-- { t="for", var=..., from=E, to=E, step=E|nil, body={...} }
-- { t="funcdef", name=..., func=F }
-- { t="return", e=E|nil }
-- { t="expr", e=E }
--
-- All parser state lives in globals prefixed PAR_ (closures do not
-- capture outer locals in catscript).
PAR_TOKS = {}
PAR_I = 0
PAR_N = 0
PAR_ERR = ""
function par_init(toks)
PAR_TOKS = toks
PAR_I = 1
PAR_N = len(toks)
PAR_ERR = ""
end
function par_cur()
if PAR_I <= PAR_N then
return PAR_TOKS[PAR_I]
end
return { kind = "EOF", text = "", line = 0 }
end
function par_at(kind)
return par_cur().kind == kind
end
function par_advance()
local t = par_cur()
if PAR_I <= PAR_N then
PAR_I = PAR_I + 1
end
return t
end
function par_fail(msg)
PAR_ERR = "line " .. tostring(par_cur().line) .. ": " .. msg
return nil
end
function par_expect(kind, what)
if par_at(kind) then
return par_advance()
end
par_fail("expected " .. what .. ", got " .. par_cur().kind)
return nil
end
-- forward decls (filled below; catscript resolves globals at call time)
function par_block() return {} end
function par_expr() return { t = "nil" } end
-- ---- expressions -----------------------------------------------------
function par_primary()
local t = par_cur()
local k = t.kind
if k == "nil" then par_advance() return { t = "nil" } end
if k == "true" then par_advance() return { t = "true" } end
if k == "false" then par_advance() return { t = "false" } end
if k == "INT" then par_advance() return { t = "int", v = tonumber(t.text) } end
if k == "FLOAT" then par_advance() return { t = "float", v = tonumber(t.text) } end
if k == "STRING" then par_advance() return { t = "str", v = t.text } end
if k == "NAME" then par_advance() return { t = "name", v = t.text } end
if k == "(" then
par_advance()
local e = par_expr()
par_expect(")", "')'")
return e
end
if k == "function" then
par_advance()
return par_funcbody("anon")
end
if k == "{" then
return par_table()
end
par_fail("unexpected token " .. k)
return { t = "nil" }
end
function par_table()
par_advance() -- {
local fields = {}
local n = 0
while not par_at("}") and not par_at("EOF") do
local fkey = nil
if par_at("NAME") and PAR_TOKS[PAR_I + 1] ~= nil and PAR_TOKS[PAR_I + 1].kind == "=" then
fkey = par_advance().text
par_advance() -- =
end
local v = par_expr()
n = n + 1
fields[n] = { k = fkey, v = v }
if not (par_at(",") or par_at(";")) then
break
end
par_advance()
end
par_expect("}", "'}'")
return { t = "table", fields = fields }
end
function par_args()
par_advance() -- (
local args = {}
local n = 0
while not par_at(")") and not par_at("EOF") do
local e = par_expr()
n = n + 1
args[n] = e
if not par_at(",") then
break
end
par_advance()
end
par_expect(")", "')'")
return args
end
function par_suffixes(e)
local go = true
while go do
if par_at(".") then
par_advance()
local nm = par_expect("NAME", "attribute name")
e = { t = "attr", obj = e, name = nm.text }
elseif par_at("[") then
par_advance()
local idx = par_expr()
par_expect("]", "']'")
e = { t = "index", obj = e, idx = idx }
elseif par_at(":") then
par_advance()
local nm = par_expect("NAME", "method name")
local args = par_args()
e = { t = "method", obj = e, name = nm.text, args = args }
elseif par_at("(") then
local args = par_args()
e = { t = "call", f = e, args = args }
else
go = false
end
end
return e
end
function par_unary()
if par_at("-") then
par_advance()
return { t = "un", op = "-", e = par_unary() }
end
if par_at("not") then
par_advance()
return { t = "un", op = "not", e = par_unary() }
end
if par_at("#") then
par_advance()
return { t = "un", op = "#", e = par_unary() }
end
return par_suffixes(par_primary())
end
function par_bp(k)
if k == "or" then return 1 end
if k == "and" then return 2 end
if k == "==" or k == "~=" or k == "<" or k == "<=" or k == ">" or k == ">=" then return 3 end
if k == ".." then return 4 end
if k == "+" or k == "-" then return 5 end
if k == "*" or k == "/" or k == "%" then return 6 end
return 0
end
function par_expr_bp(minbp)
local l = par_unary()
while true do
local k = par_cur().kind
local bp = par_bp(k)
if bp == 0 or bp < minbp then
break
end
par_advance()
local r = par_expr_bp(bp + 1)
l = { t = "bin", op = k, l = l, r = r }
end
return l
end
function par_expr()
return par_expr_bp(1)
end
-- ---- statements ------------------------------------------------------
function par_funcbody(name)
par_expect("(", "'('")
local params = {}
local np = 0
while not par_at(")") and not par_at("EOF") do
local nm = par_expect("NAME", "parameter name")
np = np + 1
params[np] = nm.text
if par_at(":") then
par_advance()
par_advance() -- type hint name (advisory)
end
if not par_at(",") then
break
end
par_advance()
end
par_expect(")", "')'")
if par_at("->") then
par_advance()
par_advance() -- return type hint (advisory)
end
local body = par_block()
par_expect("end", "'end'")
return { t = "func", name = name, params = params, body = body }
end
function par_stat()
local t = par_cur()
local k = t.kind
if k == ";" then par_advance() return nil end
if k == "local" then
par_advance()
if par_at("function") then
par_advance()
local nm = par_expect("NAME", "function name")
local f = par_funcbody(nm.text)
return { t = "local", name = nm.text, init = f }
end
local nm = par_expect("NAME", "local name")
if par_at(":") then
par_advance()
par_advance()
end
local init = nil
if par_at("=") then
par_advance()
init = par_expr()
end
return { t = "local", name = nm.text, init = init }
end
if k == "function" then
par_advance()
local nm = par_expect("NAME", "function name")
local f = par_funcbody(nm.text)
return { t = "funcdef", name = nm.text, func = f }
end
if k == "if" then
par_advance()
local conds = {}
local nc = 0
local cond = par_expr()
par_expect("then", "'then'")
nc = nc + 1
conds[nc] = { cond = cond, body = par_block() }
while par_at("elseif") do
par_advance()
local c2 = par_expr()
par_expect("then", "'then'")
nc = nc + 1
conds[nc] = { cond = c2, body = par_block() }
end
local els = nil
if par_at("else") then
par_advance()
els = par_block()
end
par_expect("end", "'end'")
return { t = "if", conds = conds, els = els }
end
if k == "while" then
par_advance()
local cond = par_expr()
par_expect("do", "'do'")
local body = par_block()
par_expect("end", "'end'")
return { t = "while", cond = cond, body = body }
end
if k == "repeat" then
par_advance()
local body = par_block()
par_expect("until", "'until'")
local cond = par_expr()
return { t = "repeat", body = body, cond = cond }
end
if k == "for" then
par_advance()
local nm = par_expect("NAME", "loop variable")
if par_at(":") then
par_advance()
par_advance()
end
par_expect("=", "'='")
local from = par_expr()
par_expect(",", "','")
local to = par_expr()
local step = nil
if par_at(",") then
par_advance()
step = par_expr()
end
par_expect("do", "'do'")
local body = par_block()
par_expect("end", "'end'")
return { t = "for", var = nm.text, from = from, to = to, step = step, body = body }
end
if k == "return" then
par_advance()
local e = nil
if not (par_at("end") or par_at("EOF") or par_at(";") or par_at("else")
or par_at("elseif") or par_at("until")) then
e = par_expr()
end
if par_at(";") then par_advance() end
return { t = "return", e = e }
end
-- assignment or expression statement
if k == "NAME" then
local nxt = PAR_TOKS[PAR_I + 1]
if nxt ~= nil and (nxt.kind == "=" or nxt.kind == "[" or nxt.kind == ".") then
-- could still be a call/index expression; disambiguate
local nm = par_advance().text
if par_at("=") then
par_advance()
local v = par_expr()
return { t = "assign", name = nm, value = v }
end
if par_at("[") then
par_advance()
local idx = par_expr()
par_expect("]", "']'")
if par_at("=") then
par_advance()
local v = par_expr()
return { t = "setidx", name = nm, idx = idx, value = v }
end
-- not an assignment: rebuild as expression
local base = par_suffixes({ t = "name", v = nm })
-- base already consumed [idx]; wrap
return { t = "expr", e = base }
end
if par_at(".") then
par_advance()
local attr = par_expect("NAME", "attribute")
if par_at("=") then
par_advance()
local v = par_expr()
return { t = "setattr", name = nm, attr = attr.text, value = v }
end
local base = par_suffixes({ t = "attr", obj = { t = "name", v = nm }, name = attr.text })
return { t = "expr", e = base }
end
end
end
local e = par_expr()
return { t = "expr", e = e }
end
function par_block()
local stats = {}
local n = 0
while not (par_at("end") or par_at("EOF") or par_at("else")
or par_at("elseif") or par_at("until")) do
local before = PAR_I
local s = par_stat()
if s ~= nil then
n = n + 1
stats[n] = s
end
if PAR_I == before then
par_fail("parse error near " .. par_cur().kind)
break
end
end
return stats
end
function par_parse(toks)
par_init(toks)
local body = par_block()
if PAR_ERR ~= "" then
return { ok = false, err = PAR_ERR }
end
return { ok = true, body = body }
end
+138
View File
@@ -0,0 +1,138 @@
/*
* main.c -- catscript CLI.
*
* Naming rule: this file lives at the project root, so its symbols are
* main_* (top-level program entry). We keep helpers static and named
* after their file, e.g. main_run_file().
*
* Modes:
* catscript <file.cat> run a script
* catscript --dump <file> print bytecode instead of running
* catscript --help usage
* catscript REPL (until EOF)
*/
#include "cat/compiler.h"
#include "cat/bytecode.h"
#include "cat/vm.h"
#include "cat/module.h"
#include "cat/stdlib/stdlib.h"
#include "cat/stdlib/build.h"
#include "cat/error.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *main_read_file(const char *path)
{
FILE *f = fopen(path, "rb");
long sz;
char *buf;
if (f == NULL)
return NULL;
fseek(f, 0, SEEK_END);
sz = ftell(f);
fseek(f, 0, SEEK_SET);
buf = malloc((size_t)sz + 1);
if (buf == NULL) {
fclose(f);
return NULL;
}
if (fread(buf, 1, (size_t)sz, f) != (size_t)sz) {
/* short read is fine for text */
}
buf[sz] = '\0';
fclose(f);
return buf;
}
static int main_run_source(const char *source, int dump)
{
CAT_ERROR_Error err;
CAT_BYTECODE_Function *fn;
CAT_VM_State *vm;
CAT_VALUE_Value *out = NULL;
int rc;
cat_error_clear(&err);
fn = cat_compiler_compile(source, &err);
if (fn == NULL) {
fprintf(stderr, "catscript: %s\n", err.message);
return 1;
}
if (dump) {
cat_bytecode_dump(fn, stdout);
cat_bytecode_function_free(fn);
return 0;
}
vm = cat_vm_new();
if (vm == NULL) {
cat_bytecode_function_free(fn);
return 1;
}
cat_stdlib_stdlib_install(vm);
cat_stdlib_build_install(vm);
rc = cat_vm_run(vm, fn, &out);
if (rc != 0)
fprintf(stderr, "catscript: %s\n", vm->err.message);
cat_vm_free(vm);
cat_bytecode_function_free(fn);
return rc != 0;
}
static void main_repl(void)
{
char line[1024];
printf("catscript REPL -- type an expression; EOF to exit.\n");
for (;;) {
printf("> ");
fflush(stdout);
if (fgets(line, sizeof(line), stdin) == NULL)
break;
main_run_source(line, 0);
}
}
static void main_usage(void)
{
printf("catscript -- a small Lua-like scripting language\n\n");
printf("usage:\n");
printf(" catscript <file.cat> run a script\n");
printf(" catscript --dump <file> print compiled bytecode\n");
printf(" catscript --help show this help\n");
printf(" catscript start a REPL\n");
}
int main(int argc, char **argv)
{
if (argc >= 2 && strcmp(argv[1], "--help") == 0) {
main_usage();
return 0;
}
if (argc >= 3 && strcmp(argv[1], "--dump") == 0) {
char *src = main_read_file(argv[2]);
int rc;
if (src == NULL) {
fprintf(stderr, "catscript: cannot read %s\n", argv[2]);
return 1;
}
rc = main_run_source(src, 1);
free(src);
return rc;
}
if (argc >= 2) {
char *src = main_read_file(argv[1]);
int rc;
if (src == NULL) {
fprintf(stderr, "catscript: cannot read %s\n", argv[1]);
return 1;
}
rc = main_run_source(src, 0);
free(src);
return rc;
}
main_repl();
return 0;
}