From ef305e7824b616e8d6989293a85df80c451b9240 Mon Sep 17 00:00:00 2001 From: Minus Date: Mon, 16 Nov 2026 01:53:53 +0000 Subject: [PATCH] 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 --- README.md | 46 +++++++++++++++ examples/classes.cat | 32 +++++++++++ include/cat/lexer.h | 3 +- src/cat/compiler.c | 73 ++++++++++++++++++++++++ src/cat/lexer.c | 6 +- src/cat/stdlib/stdlib.c | 50 ++++++++++++++++ src/cat/types/table.c | 22 +++++++ std/fs/fs.cat | 42 ++++++++++++++ std/io/io.cat | 41 +++++++++++++ {src/catscript => std/lang}/checker.cat | 0 {src/catscript => std/lang}/compiler.cat | 0 {src/catscript => std/lang}/lexer.cat | 0 {src/catscript => std/lang}/parser.cat | 0 std/math/math.cat | 16 ++++++ tests/run_tests.sh | 16 ++++++ tests/selfhost_compile.cat | 8 +-- tests/selfhost_lexer.cat | 2 +- tests/selfhost_parser.cat | 4 +- tests/std.cat | 18 ++++++ 19 files changed, 370 insertions(+), 9 deletions(-) create mode 100644 examples/classes.cat create mode 100644 std/fs/fs.cat create mode 100644 std/io/io.cat rename {src/catscript => std/lang}/checker.cat (100%) rename {src/catscript => std/lang}/compiler.cat (100%) rename {src/catscript => std/lang}/lexer.cat (100%) rename {src/catscript => std/lang}/parser.cat (100%) create mode 100644 std/math/math.cat create mode 100644 tests/std.cat diff --git a/README.md b/README.md index 131f5ad..50f91c9 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,52 @@ except e end ``` +## Estrutura de diretórios + +``` +include/cat/ headers C (todos os .h, mesmo os internos) +src/ fontes C (todos os .c) +std/ biblioteca padrão em catscript + lang/ lexer.cat, parser.cat, checker.cat, compiler.cat + io/ io.cat (print_lines, join, read_text, write_text) + fs/ fs.cat (fs_read, fs_write, fs_append, fs_copy) + math/ math.cat (double, square, abs) +examples/ programas de exemplo +tests/ suíte de testes +``` + +## `use` — importar módulos + +`use "caminho.cat"` lê, compila e executa outro arquivo catscript no +mesmo VM, tornando suas definições disponíveis (é o mecanismo de +import/require da linguagem): + +```lua +use "std/math/math.cat" +print(double(21)) -- 42 +``` + +## `class` — classes e herança + +`class NAME [extends BASE] ... end` constrói uma classe. Cada +`function m(...) end` vira um método; `extends` define a base (`__index`), +de modo que subclasses herdam métodos; e um construtor `new` padrão é +instalado (um `init(self, ...)` opcional roda na construção): + +```lua +class Animal + function init(self, name) self.name = name end + function speak(self) return self.name .. " makes a sound" end +end + +class Dog extends Animal + function speak(self) return self.name .. " barks" end +end + +local d = Dog("Rex") -- constrói via `new` +print(d:speak()) -- Rex barks +``` + ## cpk — Cat Package Manager O primeiro programa em catscript. Lê o `package.toml` de um pacote diff --git a/examples/classes.cat b/examples/classes.cat new file mode 100644 index 0000000..9bd98a4 --- /dev/null +++ b/examples/classes.cat @@ -0,0 +1,32 @@ +-- examples/classes.cat -- the `class` syntax and `use` (import). + +class Animal + function init(self, name) + self.name = name + end + function speak(self) + return self.name .. " makes a sound" + end + function get_name(self) + return self.name + end +end + +class Dog extends Animal + function speak(self) + return self.name .. " barks" + end +end + +local a = Animal("cat") +print(a:speak()) +print(a:get_name()) + +-- subclassing: Dog inherits init/get_name, overrides speak +local d = Dog("Rex") +print(d:speak()) +print(d:get_name()) + +-- use: import another catscript file (its definitions become global here) +use "std/math/math.cat" +print("double 21 =", double(21)) diff --git a/include/cat/lexer.h b/include/cat/lexer.h index 490030c..d1231a8 100644 --- a/include/cat/lexer.h +++ b/include/cat/lexer.h @@ -27,7 +27,8 @@ enum CAT_LEXER_Kind { CAT_LEXER_TOK_REPEAT, CAT_LEXER_TOK_RETURN, CAT_LEXER_TOK_THEN, CAT_LEXER_TOK_TRUE, CAT_LEXER_TOK_UNTIL, CAT_LEXER_TOK_WHILE, CAT_LEXER_TOK_YIELD, CAT_LEXER_TOK_TRY, CAT_LEXER_TOK_EXCEPT, - CAT_LEXER_TOK_RAISE, + CAT_LEXER_TOK_RAISE, CAT_LEXER_TOK_USE, CAT_LEXER_TOK_CLASS, + CAT_LEXER_TOK_EXTENDS, /* symbols */ CAT_LEXER_TOK_PLUS, CAT_LEXER_TOK_MINUS, CAT_LEXER_TOK_STAR, CAT_LEXER_TOK_SLASH, CAT_LEXER_TOK_PERCENT, CAT_LEXER_TOK_CARET, diff --git a/src/cat/compiler.c b/src/cat/compiler.c index f529667..d5931ce 100644 --- a/src/cat/compiler.c +++ b/src/cat/compiler.c @@ -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] 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) && diff --git a/src/cat/lexer.c b/src/cat/lexer.c index 91b6f48..0ec9e53 100644 --- a/src/cat/lexer.c +++ b/src/cat/lexer.c @@ -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]; diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c index eabef0f..1234b34 100644 --- a/src/cat/stdlib/stdlib.c +++ b/src/cat/stdlib/stdlib.c @@ -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)); diff --git a/src/cat/types/table.c b/src/cat/types/table.c index a4017ff..ee4abee 100644 --- a/src/cat/types/table.c +++ b/src/cat/types/table.c @@ -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, diff --git a/std/fs/fs.cat b/std/fs/fs.cat new file mode 100644 index 0000000..6b1c79c --- /dev/null +++ b/std/fs/fs.cat @@ -0,0 +1,42 @@ +-- std/fs/fs.cat -- filesystem helpers (standard library module). +-- +-- Builds on the File family (AbstractFile/File/StringIO/BytesIO). +-- Use: use "std/fs/fs.cat" + +-- Read a whole file, returning its contents ("" when missing). +function fs_read(path) + local f = File::open(path, "r") + if f == nil then + return "" + end + local data = f:read() + f:close() + return data +end + +-- Write text to a file, replacing its contents. +function fs_write(path, text) + local f = File::open(path, "w") + if f == nil then + return false + end + f:write(text) + f:close() + return true +end + +-- Append text to a file. +function fs_append(path, text) + local f = File::open(path, "a") + if f == nil then + return false + end + f:write(text) + f:close() + return true +end + +-- Copy a file's bytes from `src` to `dst`. +function fs_copy(src, dst) + return fs_write(dst, fs_read(src)) +end diff --git a/std/io/io.cat b/std/io/io.cat new file mode 100644 index 0000000..a240f86 --- /dev/null +++ b/std/io/io.cat @@ -0,0 +1,41 @@ +-- std/io/io.cat -- input/output helpers (standard library module). +-- +-- Thin, catscript-level conveniences over the C-provided natives. +-- Use: use "std/io/io.cat" + +-- Print each argument on its own line. +function print_lines(a) + local i = 1 + while i <= len(a) do + print(a[i]) + i = i + 1 + end +end + +-- Join a list's items with a separator, returning one string. +function join(a, sep) + local out = "" + local i = 1 + while i <= len(a) do + if i > 1 then + out = out .. sep + end + out = out .. tostring(a[i]) + i = i + 1 + end + return out +end + +-- Read a whole file as text ("" when missing). +function read_text(path) + local s = read_file(path) + if s == nil then + return "" + end + return s +end + +-- Write text to a file, returning bytes written. +function write_text(path, text) + return write_file(path, text) +end diff --git a/src/catscript/checker.cat b/std/lang/checker.cat similarity index 100% rename from src/catscript/checker.cat rename to std/lang/checker.cat diff --git a/src/catscript/compiler.cat b/std/lang/compiler.cat similarity index 100% rename from src/catscript/compiler.cat rename to std/lang/compiler.cat diff --git a/src/catscript/lexer.cat b/std/lang/lexer.cat similarity index 100% rename from src/catscript/lexer.cat rename to std/lang/lexer.cat diff --git a/src/catscript/parser.cat b/std/lang/parser.cat similarity index 100% rename from src/catscript/parser.cat rename to std/lang/parser.cat diff --git a/std/math/math.cat b/std/math/math.cat new file mode 100644 index 0000000..8b7ec57 --- /dev/null +++ b/std/math/math.cat @@ -0,0 +1,16 @@ +-- std/math/math.cat -- tiny math helpers (standard library module). + +function double(x) + return x * 2 +end + +function square(x) + return x * x +end + +function abs(x) + if x < 0 then + return -x + end + return x +end diff --git a/tests/run_tests.sh b/tests/run_tests.sh index 9fb4532..926e1bd 100644 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -90,6 +90,22 @@ check "slot-path" "path: /tmp/catscript_slots_demo.txt" "`echo "$out" | sed -n 1 check "slot-mode" "mode: 2" "`echo "$out" | sed -n 2p`" check "slot-closed" "closed: false" "`echo "$out" | sed -n 3p`" check "slot-closed-2" "closed: true" "`echo "$out" | sed -n 4p`" + +# ---- class / extends / use (import) --------------------------------- + +out=`$BIN examples/classes.cat` +check "class-method" "cat makes a sound" "`echo "$out" | sed -n 1p`" +check "class-attr" "cat" "`echo "$out" | sed -n 2p`" +check "class-override" "Rex barks" "`echo "$out" | sed -n 3p`" +check "class-inherit" "Rex" "`echo "$out" | sed -n 4p`" +check "class-use" "double 21 = 42" "`echo "$out" | sed -n 5p`" + +# ---- std/ tree modules (use "std/...") ------------------------------- + +out=`$BIN tests/std.cat` +check "std-math" "math double: 42" "`echo "$out" | sed -n 1p`" +check "std-io" "io join: a-b-c" "`echo "$out" | sed -n 4p`" +check "std-fs" "fs copy: true" "`echo "$out" | sed -n 6p`" # ---- bytecode dump --------------------------------------------------- out=`$BIN --dump examples/hello.cat` diff --git a/tests/selfhost_compile.cat b/tests/selfhost_compile.cat index 7aa2caa..c940397 100644 --- a/tests/selfhost_compile.cat +++ b/tests/selfhost_compile.cat @@ -5,10 +5,10 @@ -- This proves the front-end is self-hosted: given catscript source text, -- the catscript programs compile it to bytecode and execute it. -dofile("src/catscript/lexer.cat") -dofile("src/catscript/parser.cat") -dofile("src/catscript/checker.cat") -dofile("src/catscript/compiler.cat") +dofile("std/lang/lexer.cat") +dofile("std/lang/parser.cat") +dofile("std/lang/checker.cat") +dofile("std/lang/compiler.cat") function selfhost_compile(src) local toks = lexer_tokenize(src) diff --git a/tests/selfhost_lexer.cat b/tests/selfhost_lexer.cat index 3bdf100..e9d2e7a 100644 --- a/tests/selfhost_lexer.cat +++ b/tests/selfhost_lexer.cat @@ -1,7 +1,7 @@ -- tests/selfhost_lexer.cat -- drives the catscript lexer (written in -- catscript) and prints the token stream for a sample program. -dofile("src/catscript/lexer.cat") +dofile("std/lang/lexer.cat") local src = "local x : int = 42 -- note\nfunction f(a, b)\n return a + b * 2.5\nend\nprint(f(1, 2) .. \"!\")" diff --git a/tests/selfhost_parser.cat b/tests/selfhost_parser.cat index 9578c62..357a562 100644 --- a/tests/selfhost_parser.cat +++ b/tests/selfhost_parser.cat @@ -1,8 +1,8 @@ -- tests/selfhost_parser.cat -- drives the catscript parser (written in -- catscript), printing a compact dump of the AST. -dofile("src/catscript/lexer.cat") -dofile("src/catscript/parser.cat") +dofile("std/lang/lexer.cat") +dofile("std/lang/parser.cat") local src = "local x : int = 42\nfunction add(a, b)\n return a + b * 2\nend\nprint(add(x, 1) .. \"!\")" diff --git a/tests/std.cat b/tests/std.cat new file mode 100644 index 0000000..bdb1a08 --- /dev/null +++ b/tests/std.cat @@ -0,0 +1,18 @@ +-- tests/std.cat -- exercises the std/ tree (use/import + modules). + +use "std/math/math.cat" +use "std/io/io.cat" +use "std/fs/fs.cat" + +print("math double:", double(21)) +print("math square:", square(9)) +print("math abs:", abs(-7)) + +print("io join:", join({ "a", "b", "c" }, "-")) + +local path = "/tmp/catscript_std_test.txt" +fs_write(path, "one") +fs_append(path, "two") +print("fs read:", fs_read(path)) +print("fs copy:", fs_copy(path, "/tmp/catscript_std_copy.txt")) +print("fs read2:", fs_read("/tmp/catscript_std_copy.txt"))