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:
Minus committed 2026-11-16 01:53:53 +00:00
1 parent 3c20496c78
commit ef305e7824
19 files changed
+370 -9

No files matched your search

+50
View File
@@ -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));