Files
catscript/src/cat/compiler.c
T
Minus 96e8f516cc type checker, phase 2: return hints checked
- parse the `-> T` return hint into the function context (was consumed
  and dropped).
- `return <literal>` is checked against the declared return type: a
  concrete mismatch raises at compile time.  Opaque/unknown returns and
  non-literal expressions stay permissive.
- tests/types.cat + suite: a valid `-> int` function.  Suite 140 -> 141.
2026-11-18 17:15:42 +00:00

1261 lines
35 KiB
C

/*
* 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 "cat/types/type.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];
CAT_TYPES_TYPE_Type *local_types[MAXLOCALS]; /* declared/inferred */
CAT_TYPES_TYPE_Type *ret_type; /* declared `-> T` (or any) */
int nlocals;
int is_generator; /* body used `yield` */
} 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;
int repl; /* REPL mode: a lone expression is echoed */
} 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)
{
CAT_VALUE_Value *v = cat_types_ascii_text_new(s);
int k = cat_bytecode_add_const(cur_fn(c), v);
cat_value_release(v); /* pool owns it now */
return k;
}
/* Add a freshly-created constant: the pool takes a reference, we drop
* ours, so the constant lives exactly as long as the chunk. */
static int add_const_owned(Compiler *c, CAT_VALUE_Value *v)
{
int k = cat_bytecode_add_const(cur_fn(c), v);
cat_value_release(v);
return k;
}
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);
f->local_types[slot] = NULL;
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_IS: 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;
}
}
/* Parse an optional type hint: e.g. `: int`, `: cbyte[]`,
* `: DynSized()`, `: sentinel_sized<0>`. We consume a full balanced
* expression (ignoring `()`, `<>`, `[]` nesting) and return the
* descriptor of the FIRST identifier -- structural typing: the first
* name IS the type. With no `:` it returns `any`. */
static CAT_TYPES_TYPE_Type *parse_type_core(Compiler *c, int colon)
{
CAT_TYPES_TYPE_Type *t = NULL;
int depth = 0;
if (colon) {
if (!check(c, CAT_LEXER_TOK_COLON))
return cat_types_type_any();
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) {
if (t == NULL)
t = cat_types_type_named(c->tok.text);
next(c);
continue;
}
if (k == CAT_LEXER_TOK_INT || k == CAT_LEXER_TOK_STRING) {
next(c);
continue;
}
if (k == CAT_LEXER_TOK_COMMA && depth > 0) {
next(c);
continue;
}
break;
}
return (t != NULL) ? t : cat_types_type_any();
}
static CAT_TYPES_TYPE_Type *parse_type_hint(Compiler *c)
{
return parse_type_core(c, 1);
}
/* The type of the value the cursor is on, when it is a literal; NULL when
* the expression is not a simple literal (then we say nothing). */
static CAT_TYPES_TYPE_Type *literal_type(Compiler *c)
{
switch (c->tok.kind) {
case CAT_LEXER_TOK_INT: return cat_types_type_int();
case CAT_LEXER_TOK_FLOAT: return cat_types_type_float();
case CAT_LEXER_TOK_STRING: return cat_types_type_text();
case CAT_LEXER_TOK_TRUE:
case CAT_LEXER_TOK_FALSE: return cat_types_type_bool();
case CAT_LEXER_TOK_NIL: return cat_types_type_empty();
default: return NULL;
}
}
/* 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);
nc.local_types[nc.nlocals] = parse_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))
nc.ret_type = parse_type_core(c, 0);
else
nc.ret_type = cat_types_type_any();
/* push context and compile body */
c->stack[c->nstack++] = nc;
block(c);
expect(c, CAT_LEXER_TOK_END, "'end'");
/* A body that used `yield` makes this a generator. */
if (c->stack[c->nstack - 1].is_generator)
sub->is_generator = 1;
emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, c->tok.line);
c->nstack--;
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 = add_const_owned(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 = add_const_owned(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_EMPTY, 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,
add_const_owned(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,
add_const_owned(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_EMPTY, 0, 0, t.line);
next(c);
return;
}
/* suffixes */
for (;;) {
if (check(c, CAT_LEXER_TOK_DOT)) {
next(c);
/* a member name may be a keyword (glfw.false, obj.end);
* the lexer keeps the text of keyword tokens too. */
if (c->tok.kind == CAT_LEXER_TOK_NAME ||
(c->tok.kind >= CAT_LEXER_TOK_AND &&
c->tok.kind <= CAT_LEXER_TOK_EXTENDS)) {
char mname[256];
int mline = c->tok.line;
int k;
snprintf(mname, sizeof(mname), "%s", c->tok.text);
next(c);
k = add_string(c, mname);
if (check(c, CAT_LEXER_TOK_LPAREN)) {
/* a.b(args) -- method call WITH self */
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_CALLMETHOD, nargs, k,
mline);
} else {
/* a.b -- read the member (a field, or a function
* value to be called later) */
emit(c, CAT_BYTECODE_OP_GETATTR, k, 0, mline);
}
}
} else if (check(c, CAT_LEXER_TOK_DCOLON)) {
/* a::b -- static access: no `self`. `a::b(args)` calls
* `b` without the receiver; `a::b` reads the member. */
next(c);
if (c->tok.kind == CAT_LEXER_TOK_NAME ||
(c->tok.kind >= CAT_LEXER_TOK_AND &&
c->tok.kind <= CAT_LEXER_TOK_EXTENDS)) {
char mname[256];
int mline = c->tok.line;
int k;
snprintf(mname, sizeof(mname), "%s", c->tok.text);
next(c);
k = add_string(c, mname);
emit(c, CAT_BYTECODE_OP_GETATTR, k, 0, mline);
if (check(c, CAT_LEXER_TOK_LPAREN)) {
/* call the member WITHOUT self */
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, mline);
}
}
} else if (check(c, CAT_LEXER_TOK_COLON)) {
/* The old `obj:method(args)` syntax was removed. Detect it
* (name '.') and point the user at the new forms. */
size_t sp = c->lx.pos;
int sl = c->lx.line;
CAT_LEXER_Token la, nx;
cat_lexer_next(&c->lx, &la);
if (la.kind == CAT_LEXER_TOK_NAME) {
cat_lexer_next(&c->lx, &nx);
c->lx.pos = sp;
c->lx.line = sl;
if (nx.kind == CAT_LEXER_TOK_LPAREN) {
err_at(c, c->tok.line,
"the ':' method syntax was removed; "
"use '.' for obj.method(args) or "
"'::' for obj::method(args)");
c->failed = 1;
}
}
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);
if (kind == CAT_LEXER_TOK_IS)
emit(c, CAT_BYTECODE_OP_IS, 0, 0, c->tok.line);
else
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;
CAT_TYPES_TYPE_Type *decl;
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
decl = parse_type_hint(c);
if (accept(c, CAT_LEXER_TOK_ASSIGN)) {
CAT_TYPES_TYPE_Type *lit = literal_type(c);
if (lit != NULL &&
!cat_types_type_assignable(decl, lit))
err_at(c, line,
"cannot assign %s to %s",
cat_types_type_name(lit),
cat_types_type_name(decl));
expr(c);
} else {
emit(c, CAT_BYTECODE_OP_EMPTY, 0, 0, line);
}
slot = add_local(c, name);
if (slot >= 0) {
ctx(c)->local_types[slot] = decl;
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);
}
(void)parse_type_hint(c);
if (check(c, CAT_LEXER_TOK_IN)) {
/* for NAME in expr do <body> end -- iterate any iterator
* (generator). Each round calls NEXT; empty ends the loop. */
int islot;
next(c);
expr(c); /* the iterable */
expect(c, CAT_LEXER_TOK_DO, "'do'");
slot = add_local(c, var);
islot = add_local(c, " .it");
emit(c, CAT_BYTECODE_OP_SETLOCAL, islot, 0, line);
jcond = cur_fn(c)->ncode;
emit(c, CAT_BYTECODE_OP_GETLOCAL, islot, 0, line);
jend = emit(c, CAT_BYTECODE_OP_FORNEXT, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
{
int lv = c->nloops++;
c->brk_n[lv] = 0;
block(c);
c->nloops--;
emit(c, CAT_BYTECODE_OP_JUMP, jcond, 0, line);
cur_fn(c)->code[jend].a = cur_fn(c)->ncode;
{
int k;
for (k = 0; k < c->brk_n[lv]; k++)
cur_fn(c)->code[c->brk_ends[lv][k]].a =
cur_fn(c)->ncode;
}
}
expect(c, CAT_LEXER_TOK_END, "'end'");
break;
}
expect(c, CAT_LEXER_TOK_ASSIGN, "'='");
expr(c); /* start */
expect(c, CAT_LEXER_TOK_COMMA, "','");
expr(c); /* limit */
if (accept(c, CAT_LEXER_TOK_COMMA))
expr(c); /* step */
else
emit(c, CAT_BYTECODE_OP_CONST,
add_const_owned(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_USE:
/* `use name` imports a module: its source is read, compiled and
* run in the current VM, so its definitions become available
* here. The operand is a module name (`math`) or a path
* (`"std/math/math.cat"`); the runtime resolves names. */
next(c);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, "use"), 0, line);
if (check(c, CAT_LEXER_TOK_NAME)) {
emit(c, CAT_BYTECODE_OP_CONST, add_string(c, c->tok.text),
0, line);
next(c);
} else {
expr(c);
}
emit(c, CAT_BYTECODE_OP_CALL, 1, 0, line);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
accept(c, CAT_LEXER_TOK_SEMI);
break;
case CAT_LEXER_TOK_CLASS: {
/* class NAME [extends BASE] <methods> end
*
* Builds a class table: each `function m(...) end` becomes a method
* on the table, `__index` points at the base (so instances inherit),
* and a default `new` constructor fills an instance and runs the
* class's `init` if present. The table is bound to a global NAME. */
char name[256];
char base[256];
char impl[8][256];
int nimpl = 0;
int i;
next(c);
name[0] = '\0';
base[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
if (accept(c, CAT_LEXER_TOK_EXTENDS)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(base, sizeof(base), "%s", c->tok.text);
next(c);
}
}
if (check(c, CAT_LEXER_TOK_NAME) &&
strcmp(c->tok.text, "implements") == 0) {
next(c);
for (;;) {
if (check(c, CAT_LEXER_TOK_NAME)) {
if (nimpl < 8)
snprintf(impl[nimpl], sizeof(impl[0]),
"%s", c->tok.text);
nimpl++;
next(c);
}
if (!accept(c, CAT_LEXER_TOK_COMMA))
break;
}
}
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, line);
/* __index: base (inheritance) or the class itself */
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
if (base[0] != '\0')
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, base), 0, line);
else
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__index"), 0, line);
/* default constructor `new` (a user-defined `new` overrides it) */
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, "__class_new"), 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "new"), 0, line);
/* methods */
while (!check(c, CAT_LEXER_TOK_END) &&
!check(c, CAT_LEXER_TOK_EOF)) {
if (!check(c, CAT_LEXER_TOK_FUNCTION)) {
err_at(c, c->tok.line, "expected 'function' or 'end' in class");
break;
}
next(c);
{
char mname[256];
int proto;
mname[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(mname, sizeof(mname), "%s", c->tok.text);
next(c);
}
proto = compile_function_literal(c, mname);
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, mname), 0, line);
}
}
expect(c, CAT_LEXER_TOK_END, "'end'");
emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line);
/* runtime assertion: the class must satisfy each declared interface
* (structural check, performed by __implements_check). */
for (i = 0; i < nimpl && i < 8; i++) {
emit(c, CAT_BYTECODE_OP_GETGLOBAL,
add_string(c, "__implements_check"), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, impl[i]), 0, line);
emit(c, CAT_BYTECODE_OP_CALL, 2, 0, line);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
}
break;
}
case CAT_LEXER_TOK_INTERFACE: {
/* interface NAME [extends BASE] <function m(...) end> end
*
* An interface is a table tagged `__interface`; its members name the
* required methods (a body is allowed and becomes a default method,
* shared through `__index`). The `is` operator checks satisfaction
* structurally at runtime. */
char name[256];
char base[256];
next(c);
name[0] = '\0';
base[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(name, sizeof(name), "%s", c->tok.text);
next(c);
}
if (accept(c, CAT_LEXER_TOK_EXTENDS)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(base, sizeof(base), "%s", c->tok.text);
next(c);
}
}
emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, line);
/* the interface marker, so `is` knows to check structurally */
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__interface"), 0, line);
/* interface inheritance */
if (base[0] != '\0') {
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, base), 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, "__index"), 0, line);
}
while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF)) {
if (!check(c, CAT_LEXER_TOK_FUNCTION)) {
err_at(c, c->tok.line,
"expected 'function' or 'end' in interface");
break;
}
next(c);
{
char mname[256];
int proto;
mname[0] = '\0';
if (check(c, CAT_LEXER_TOK_NAME)) {
snprintf(mname, sizeof(mname), "%s", c->tok.text);
next(c);
}
proto = compile_function_literal(c, mname);
emit(c, CAT_BYTECODE_OP_DUP, 0, 0, line);
emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line);
emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, mname), 0, line);
}
}
expect(c, CAT_LEXER_TOK_END, "'end'");
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) &&
!check(c, CAT_LEXER_TOK_EXCEPT)) {
CAT_TYPES_TYPE_Type *lit = literal_type(c);
CAT_TYPES_TYPE_Type *want = ctx(c)->ret_type;
if (lit != NULL && want != NULL &&
!cat_types_type_assignable(want, lit))
err_at(c, line, "cannot return %s from function returning %s",
cat_types_type_name(lit),
cat_types_type_name(want));
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_YIELD:
/* `yield [expr]` suspends the enclosing function; its body now
* marks the function as a generator (calls return a generator). */
next(c);
if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) &&
!check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL) &&
!check(c, CAT_LEXER_TOK_EXCEPT))
expr(c);
else
emit(c, CAT_BYTECODE_OP_EMPTY, 0, 0, line);
emit(c, CAT_BYTECODE_OP_YIELD, 0, 0, line);
ctx(c)->is_generator = 1;
accept(c, CAT_LEXER_TOK_SEMI);
break;
case CAT_LEXER_TOK_RAISE:
/* `raise expr` throws the value; caught by an enclosing try. */
next(c);
if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
!check(c, CAT_LEXER_TOK_SEMI))
expr(c);
else
emit(c, CAT_BYTECODE_OP_EMPTY, 0, 0, line);
emit(c, CAT_BYTECODE_OP_RAISE, 0, 0, line);
accept(c, CAT_LEXER_TOK_SEMI);
break;
case CAT_LEXER_TOK_TRY: {
/* try <block> except [NAME] <block> end. On error the VM
* unwinds to the handler with the error value on the stack. */
int setup, jend;
next(c);
setup = emit(c, CAT_BYTECODE_OP_TRYSETUP, 0, 0, line);
block(c);
emit(c, CAT_BYTECODE_OP_TRYEND, 0, 0, line);
jend = emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line);
/* handler entry */
cur_fn(c)->code[setup].a = cur_fn(c)->ncode;
if (accept(c, CAT_LEXER_TOK_EXCEPT)) {
if (check(c, CAT_LEXER_TOK_NAME)) {
char vn[64];
int slot;
snprintf(vn, sizeof(vn), "%s", c->tok.text);
next(c);
slot = add_local(c, vn);
if (slot >= 0)
emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line);
else
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
} else {
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
}
block(c);
}
cur_fn(c)->code[jend].a = cur_fn(c)->ncode;
expect(c, CAT_LEXER_TOK_END, "'end'");
break;
}
case CAT_LEXER_TOK_NAME: {
/* assignment if `name =`, or field assignment if `name.attr =`.
* Otherwise rewind and parse as an ordinary expression. */
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) {
/* dotted assignment, possibly chained: name.a.b = value.
* Collect the attribute chain; if it ends in '=', emit the
* object expression followed by a final SETATTR. Otherwise
* rewind and parse as an ordinary expression. */
char chain[16][256];
int nchain = 0;
int is_assign = 0;
for (;;) {
CAT_LEXER_Token attr, nx;
cat_lexer_next(&c->lx, &attr);
/* a member name may be a keyword (glfw.false = 0) */
if (attr.kind != CAT_LEXER_TOK_NAME &&
!(attr.kind >= CAT_LEXER_TOK_AND &&
attr.kind <= CAT_LEXER_TOK_EXTENDS))
break;
if (nchain < 16)
snprintf(chain[nchain], sizeof(chain[0]),
"%s", attr.text);
nchain++;
cat_lexer_next(&c->lx, &nx);
if (nx.kind == CAT_LEXER_TOK_DOT)
continue;
if (nx.kind == CAT_LEXER_TOK_ASSIGN) {
c->tok = nx;
is_assign = 1;
}
break;
}
if (is_assign && nchain > 0 && nchain <= 16) {
int slot = find_local(c, name);
int k;
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);
/* walk to the object that owns the final attribute */
for (k = 0; k < nchain - 1; k++)
emit(c, CAT_BYTECODE_OP_GETATTR,
add_string(c, chain[k]), 0, line);
expr(c);
emit(c, CAT_BYTECODE_OP_SETATTR,
add_string(c, chain[nchain - 1]), 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, c->repl ? CAT_BYTECODE_OP_PRINTEXPR : 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) && !check(c, CAT_LEXER_TOK_EXCEPT)) {
int before = cur_fn(c)->ncode;
/* a lone ';' is a valid empty statement, not a parse error */
if (check(c, CAT_LEXER_TOK_SEMI)) {
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)
{
return cat_compiler_compile_mode(source, err, 0);
}
CAT_BYTECODE_Function *cat_compiler_compile_mode(const char *source,
CAT_ERROR_Error *err, int repl)
{
Compiler c;
CAT_BYTECODE_Function *fn;
memset(&c, 0, sizeof(c));
c.err = err;
c.repl = repl;
cat_lexer_init(&c.lx, source);
fn = cat_bytecode_function_new("main");
memset(&c.stack[0], 0, sizeof(c.stack[0]));
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;
}