std/ tree, use (import) and class syntax
- std/ layout: std/lang/{lexer,parser,checker,compiler}.cat moved from src/catscript
- std/io/io.cat, std/fs/fs.cat, std/math/math.cat modules
- use "path.cat": import another unit (compile+run in the same VM)
- class NAME [extends BASE] ... end: methods, inheritance via __index,
default new constructor (runs optional init), tables are callable
- examples/classes.cat, tests/std.cat; 48/48 tests
This commit is contained in:
1 parent
3c20496c78
commit
ef305e7824
19 files changed
+370
-9
No files matched your search
@@ -742,6 +742,79 @@ static void stat(Compiler *c)
|
||||
break;
|
||||
}
|
||||
|
||||
case CAT_LEXER_TOK_USE:
|
||||
/* `use expr` imports another catscript source file: it reads,
|
||||
* compiles and runs that file in the current VM (like dofile),
|
||||
* so its definitions become available here. */
|
||||
next(c);
|
||||
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, "use"), 0, line);
|
||||
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];
|
||||
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);
|
||||
/* __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);
|
||||
break;
|
||||
}
|
||||
|
||||
case CAT_LEXER_TOK_RETURN:
|
||||
next(c);
|
||||
if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) &&
|
||||
|
||||
+5
-1
@@ -18,11 +18,13 @@ struct kw {
|
||||
static const struct kw g_keywords[] = {
|
||||
{ "and", CAT_LEXER_TOK_AND },
|
||||
{ "break", CAT_LEXER_TOK_BREAK },
|
||||
{ "class", CAT_LEXER_TOK_CLASS },
|
||||
{ "do", CAT_LEXER_TOK_DO },
|
||||
{ "else", CAT_LEXER_TOK_ELSE },
|
||||
{ "elseif", CAT_LEXER_TOK_ELSEIF },
|
||||
{ "except", CAT_LEXER_TOK_EXCEPT },
|
||||
{ "end", CAT_LEXER_TOK_END },
|
||||
{ "extends", CAT_LEXER_TOK_EXTENDS },
|
||||
{ "false", CAT_LEXER_TOK_FALSE },
|
||||
{ "for", CAT_LEXER_TOK_FOR },
|
||||
{ "function", CAT_LEXER_TOK_FUNCTION },
|
||||
@@ -39,6 +41,7 @@ static const struct kw g_keywords[] = {
|
||||
{ "true", CAT_LEXER_TOK_TRUE },
|
||||
{ "try", CAT_LEXER_TOK_TRY },
|
||||
{ "until", CAT_LEXER_TOK_UNTIL },
|
||||
{ "use", CAT_LEXER_TOK_USE },
|
||||
{ "while", CAT_LEXER_TOK_WHILE },
|
||||
{ "yield", CAT_LEXER_TOK_YIELD },
|
||||
};
|
||||
@@ -261,7 +264,8 @@ const char *cat_lexer_kind_name(int kind)
|
||||
"yield", "try", "except", "raise",
|
||||
"+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<",
|
||||
">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":",
|
||||
"::", "..", "->"
|
||||
"::", "..", "->",
|
||||
"class", "extends", "use"
|
||||
};
|
||||
if (kind >= 0 && kind < (int)(sizeof(names) / sizeof(names[0])))
|
||||
return names[kind];
|
||||
|
||||
@@ -327,6 +327,54 @@ static int lf_dofile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* `use expr` -- import another catscript source file (alias of dofile),
|
||||
* so `use "std/io/file.cat"` pulls its definitions into this unit. */
|
||||
static int lf_use(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
|
||||
CAT_VALUE_Value **out)
|
||||
{
|
||||
return lf_dofile(vm, args, nargs, out);
|
||||
}
|
||||
|
||||
/* `__class_new(cls, ...)` -- default constructor installed on every
|
||||
* class as `new`. Copies the class into a fresh instance and runs the
|
||||
* class's `init` method (if any) with the given arguments. */
|
||||
static int lf_class_new(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
|
||||
CAT_VALUE_Value **out)
|
||||
{
|
||||
CAT_VALUE_Value *cls;
|
||||
CAT_VALUE_Value *inst;
|
||||
CAT_VALUE_Value *init = NULL;
|
||||
CAT_ERROR_Error e;
|
||||
int i;
|
||||
|
||||
(void)vm;
|
||||
if (nargs < 1) {
|
||||
*out = cat_types_nil_get();
|
||||
return 0;
|
||||
}
|
||||
cls = args[0];
|
||||
inst = cat_types_table_new();
|
||||
/* share the class's methods/layout with the instance */
|
||||
cat_error_clear(&e);
|
||||
cat_types_table_set(inst, "__index", cls, &e);
|
||||
cat_error_clear(&e);
|
||||
cat_types_table_set(inst, "__class", cls, &e);
|
||||
/* run init(args...) if the class defines it */
|
||||
cat_error_clear(&e);
|
||||
if (cat_value_get_attribute(cls, "init", &init, &e) == 0 &&
|
||||
init != NULL) {
|
||||
CAT_VALUE_Value *r = NULL;
|
||||
CAT_VALUE_Value *callargs[258];
|
||||
callargs[0] = inst;
|
||||
for (i = 1; i < nargs && i < 257; i++)
|
||||
callargs[i] = args[i];
|
||||
cat_error_clear(&e);
|
||||
cat_value_call(init, callargs, nargs, &r, &e);
|
||||
}
|
||||
*out = inst;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
|
||||
CAT_VALUE_Value **out)
|
||||
{
|
||||
@@ -375,6 +423,8 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
|
||||
cat_vm_register_native(vm, "chr", lf_chr);
|
||||
cat_vm_register_native(vm, "substr", lf_substr);
|
||||
cat_vm_register_native(vm, "dofile", lf_dofile);
|
||||
cat_vm_register_native(vm, "use", lf_use);
|
||||
cat_vm_register_native(vm, "__class_new", lf_class_new);
|
||||
/* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */
|
||||
cat_vm_set_global(vm, "AbstractFile",
|
||||
cat_types_native_new("AbstractFile", lf_abstractfile));
|
||||
|
||||
@@ -36,6 +36,27 @@ static int table_set_attribute(CAT_VALUE_Value *self, const char *name,
|
||||
return cat_types_table_set(self, name, value, err);
|
||||
}
|
||||
|
||||
/* Calling a table invokes its `new` method with the table as the class
|
||||
* (self). A class built by the `class` syntax installs `new` =
|
||||
* __class_new, so `Animal("cat")` constructs an instance. */
|
||||
static int table_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, int nargs,
|
||||
CAT_VALUE_Value **out, CAT_ERROR_Error *err)
|
||||
{
|
||||
CAT_VALUE_Value *ctor = NULL;
|
||||
CAT_VALUE_Value *callargs[258];
|
||||
CAT_ERROR_Error e;
|
||||
int i;
|
||||
|
||||
cat_error_clear(&e);
|
||||
if (cat_value_get_attribute(self, "new", &ctor, &e) != 0 || ctor == NULL)
|
||||
return (cat_error_raise(err,
|
||||
"table is not callable (no 'new')"), -1);
|
||||
callargs[0] = self;
|
||||
for (i = 0; i < nargs && i < 257; i++)
|
||||
callargs[i + 1] = args[i];
|
||||
return cat_value_call(ctor, callargs, nargs + 1, out, err);
|
||||
}
|
||||
|
||||
static void table_destroy(CAT_VALUE_Value *self)
|
||||
{
|
||||
CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)self;
|
||||
@@ -53,6 +74,7 @@ static void table_destroy(CAT_VALUE_Value *self)
|
||||
static CAT_VALUE_Vtable g_table_vtable = {
|
||||
.type_name = "table",
|
||||
.kind = CAT_VALUE_KIND_TABLE,
|
||||
.call = { table_call },
|
||||
.get_attribute = { table_get_attribute },
|
||||
.set_attribute = { table_set_attribute },
|
||||
.destroy = table_destroy,
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
-- 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
|
||||
@@ -1,388 +0,0 @@
|
||||
-- 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
|
||||
@@ -1,226 +0,0 @@
|
||||
-- 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
|
||||
@@ -1,425 +0,0 @@
|
||||
-- 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
|
||||
Reference in new issue
Block a user