From 52d118211fc504e983e5d45406bc7fa72d20ca57 Mon Sep 17 00:00:00 2001 From: Minus Date: Mon, 16 Nov 2026 01:27:44 +0000 Subject: [PATCH] =?UTF-8?q?catscript:=20n=C3=BAcleo=20C,=20stdlib=20(TOML)?= =?UTF-8?q?,=20fam=C3=ADlia=20de=20arquivos=20e=20front-end=20self-hosted?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Modelo de objetos Cat_Value + vtable (interfaces abstratas) - VM de bytecode, sem GIL (VM por-thread, nativas como valores) - Stdlib com TOML embutido (toml_parse/toml_encode) - Família de arquivos: AbstractFile (abstrata), File::open, StringIO, BytesIO - Front-end (lexer/parser/checker/compiler) implementado em catscript - cpk (cat package manager) como primeiro programa; manifest package.toml - Type hints advisory, inclusive DynSized() e sentinel_sized<...> - 25/25 testes passando (make test) --- .gitignore | 9 + Makefile | 78 +++ README.md | 185 +++++++ examples/arith.cat | 14 + examples/control.cat | 29 ++ examples/cpk.cat | 54 +++ examples/files.cat | 31 ++ examples/hello.cat | 5 + examples/oop.cat | 18 + examples/package.toml | 9 + examples/text.cat | 10 + examples/toml.cat | 7 + include/cat/bytecode.h | 110 +++++ include/cat/compiler.h | 20 + include/cat/error.h | 29 ++ include/cat/lexer.h | 66 +++ include/cat/module.h | 39 ++ include/cat/stdlib/build.h | 25 + include/cat/stdlib/stdlib.h | 18 + include/cat/stdlib/toml.h | 25 + include/cat/types/ascii_text.h | 21 + include/cat/types/bool.h | 21 + include/cat/types/byte.h | 21 + include/cat/types/char.h | 25 + include/cat/types/file.h | 64 +++ include/cat/types/float.h | 20 + include/cat/types/function.h | 27 ++ include/cat/types/int.h | 23 + include/cat/types/native.h | 35 ++ include/cat/types/nil.h | 20 + include/cat/types/number.h | 51 ++ include/cat/types/table.h | 42 ++ include/cat/types/text.h | 41 ++ include/cat/types/utf8_text.h | 21 + include/cat/value.h | 147 ++++++ include/cat/vm.h | 59 +++ src/cat/bytecode.c | 130 +++++ src/cat/compiler.c | 848 +++++++++++++++++++++++++++++++++ src/cat/error.c | 30 ++ src/cat/lexer.c | 264 ++++++++++ src/cat/module.c | 60 +++ src/cat/stdlib/build.c | 132 +++++ src/cat/stdlib/stdlib.c | 387 +++++++++++++++ src/cat/stdlib/toml.c | 408 ++++++++++++++++ src/cat/types/ascii_text.c | 52 ++ src/cat/types/bool.c | 35 ++ src/cat/types/byte.c | 53 +++ src/cat/types/char.c | 65 +++ src/cat/types/file.c | 358 ++++++++++++++ src/cat/types/float.c | 53 +++ src/cat/types/function.c | 61 +++ src/cat/types/int.c | 53 +++ src/cat/types/native.c | 59 +++ src/cat/types/nil.c | 31 ++ src/cat/types/number.c | 122 +++++ src/cat/types/table.c | 136 ++++++ src/cat/types/text.c | 64 +++ src/cat/types/utf8_text.c | 75 +++ src/cat/value.c | 135 ++++++ src/cat/vm.c | 433 +++++++++++++++++ src/catscript/checker.cat | 132 +++++ src/catscript/compiler.cat | 388 +++++++++++++++ src/catscript/lexer.cat | 226 +++++++++ src/catscript/parser.cat | 425 +++++++++++++++++ src/main.c | 138 ++++++ tests/run_tests.sh | 94 ++++ tests/selfhost_compile.cat | 37 ++ tests/selfhost_lexer.cat | 14 + tests/selfhost_parser.cat | 21 + 69 files changed, 6938 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 examples/arith.cat create mode 100644 examples/control.cat create mode 100644 examples/cpk.cat create mode 100644 examples/files.cat create mode 100644 examples/hello.cat create mode 100644 examples/oop.cat create mode 100644 examples/package.toml create mode 100644 examples/text.cat create mode 100644 examples/toml.cat create mode 100644 include/cat/bytecode.h create mode 100644 include/cat/compiler.h create mode 100644 include/cat/error.h create mode 100644 include/cat/lexer.h create mode 100644 include/cat/module.h create mode 100644 include/cat/stdlib/build.h create mode 100644 include/cat/stdlib/stdlib.h create mode 100644 include/cat/stdlib/toml.h create mode 100644 include/cat/types/ascii_text.h create mode 100644 include/cat/types/bool.h create mode 100644 include/cat/types/byte.h create mode 100644 include/cat/types/char.h create mode 100644 include/cat/types/file.h create mode 100644 include/cat/types/float.h create mode 100644 include/cat/types/function.h create mode 100644 include/cat/types/int.h create mode 100644 include/cat/types/native.h create mode 100644 include/cat/types/nil.h create mode 100644 include/cat/types/number.h create mode 100644 include/cat/types/table.h create mode 100644 include/cat/types/text.h create mode 100644 include/cat/types/utf8_text.h create mode 100644 include/cat/value.h create mode 100644 include/cat/vm.h create mode 100644 src/cat/bytecode.c create mode 100644 src/cat/compiler.c create mode 100644 src/cat/error.c create mode 100644 src/cat/lexer.c create mode 100644 src/cat/module.c create mode 100644 src/cat/stdlib/build.c create mode 100644 src/cat/stdlib/stdlib.c create mode 100644 src/cat/stdlib/toml.c create mode 100644 src/cat/types/ascii_text.c create mode 100644 src/cat/types/bool.c create mode 100644 src/cat/types/byte.c create mode 100644 src/cat/types/char.c create mode 100644 src/cat/types/file.c create mode 100644 src/cat/types/float.c create mode 100644 src/cat/types/function.c create mode 100644 src/cat/types/int.c create mode 100644 src/cat/types/native.c create mode 100644 src/cat/types/nil.c create mode 100644 src/cat/types/number.c create mode 100644 src/cat/types/table.c create mode 100644 src/cat/types/text.c create mode 100644 src/cat/types/utf8_text.c create mode 100644 src/cat/value.c create mode 100644 src/cat/vm.c create mode 100644 src/catscript/checker.cat create mode 100644 src/catscript/compiler.cat create mode 100644 src/catscript/lexer.cat create mode 100644 src/catscript/parser.cat create mode 100644 src/main.c create mode 100644 tests/run_tests.sh create mode 100644 tests/selfhost_compile.cat create mode 100644 tests/selfhost_lexer.cat create mode 100644 tests/selfhost_parser.cat diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..adc676d --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# catscript build artifacts +build/ +*.o +*.a +*.zip +*.out +# editor / OS noise +*.swp +.DS_Store diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..88ce704 --- /dev/null +++ b/Makefile @@ -0,0 +1,78 @@ +# Makefile -- catscript +# +# Naming rule: every function/type name in the sources encodes its path +# from the project root with '/' -> '_'. A function in a/b/c.h is named +# a_b_c_funcao(); a type there is A_B_C_MeuTipo. (Headers keep the +# `include/` root and sources the `src/` root out of the name, so +# include/cat/types/int.h and src/cat/types/int.c are both module +# `cat_types_int`.) +# +# Targets (run `make help` for the list): +# help show this list (default goal) +# all build the catscript binary +# test build and run the automated test suite +# clean remove build artifacts + +CC ?= cc +CFLAGS ?= -std=c11 -Wall -Wextra -O2 -Wno-unused-parameter -D_DEFAULT_SOURCE +CPPFLAGS += -Iinclude +LDFLAGS ?= +LDLIBS ?= -lm + +BUILD := build/catscript +BIN := $(BUILD)/catscript + +SRCS := \ + src/main.c \ + src/cat/error.c \ + src/cat/value.c \ + src/cat/bytecode.c \ + src/cat/lexer.c \ + src/cat/compiler.c \ + src/cat/vm.c \ + src/cat/module.c \ + src/cat/types/nil.c \ + src/cat/types/bool.c \ + src/cat/types/number.c \ + src/cat/types/int.c \ + src/cat/types/float.c \ + src/cat/types/byte.c \ + src/cat/types/char.c \ + src/cat/types/ascii_text.c \ + src/cat/types/utf8_text.c \ + src/cat/types/text.c \ + src/cat/types/table.c \ + src/cat/types/function.c \ + src/cat/types/native.c \ + src/cat/types/file.c \ + src/cat/stdlib/stdlib.c \ + src/cat/stdlib/toml.c \ + src/cat/stdlib/build.c + +OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) + +.PHONY: help all test clean examples + +# Default goal: print the help. +help: + @echo "catscript build targets:" + @echo " make all - build the catscript binary ($(BIN))" + @echo " make test - build and run the automated test suite" + @echo " make clean - remove build artifacts" + @echo " make help - show this help (default goal)" + +all: $(BIN) + +$(BIN): $(OBJS) + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LDLIBS) + +$(BUILD)/%.o: src/%.c + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $< + +test: $(BIN) + @sh tests/run_tests.sh + +clean: + rm -rf build/catscript diff --git a/README.md b/README.md new file mode 100644 index 0000000..789989d --- /dev/null +++ b/README.md @@ -0,0 +1,185 @@ +# catscript + +Uma linguagem de scripting pequena, escrita em C, **100% orientada a +objetos**, com sintaxe parecida com Lua e **tipagem estrutural**. + +Este repositório contém: + +- a **C API amigável** (`include/cat/`): modelo de objetos, tipos, + bytecode, VM, stdlib; +- o **front-end self-hosted** (`src/catscript/*.cat`): lexer, parser, + checker e compiler **escritos na própria catscript**; +- a **biblioteca padrão** (incluindo TOML); +- `cpk`, o **Cat Package Manager** — o primeiro programa real em catscript; +- `examples/` e `tests/` automatizados. + +## Build + +```sh +make # igual a `make all`; constrói build/catscript/catscript +make test # constrói e roda a suíte automatizada +make help # lista os alvos (alvo padrão) +make clean # remove artefatos +``` + +## Uso + +```sh +catscript programa.cat # executa um script +catscript --dump prog.cat # imprime o bytecode compilado +catscript --help # ajuda +catscript # REPL +``` + +## A C API amigável + +Todo valor é um objeto: um ponteiro `Cat_Value*` cujo primeiro membro é +uma vtable (`Cat_ValueType`). O vtable carrega uma interface por operação; +um slot vazio vira erro estruturado, nunca crash. + +Interfaces abstratas: + +| Interface | Papel | +|---|---| +| `Cat_ValueType` | vtable: nome, kind, slots de operação | +| `Cat_ImplementsAdd/Sub/Mul/Div/Rem` | operadores binários | +| `Cat_ImplementsCall` | chamada (`self(args...)`) | +| `Cat_ImplementsRaise` | levantar erro a partir do objeto | +| `Cat_ImplementsGetAttribute` | `self.nome` | +| `Cat_ImplementsSetAttribute` | `self.nome = valor` | + +Tipos abstratos: `Cat_Module`, `Cat_Number`, `Cat_Text`. + +Tipos concretos: `int`, `float`, `byte`, `char1`, `char2`, `char3`, +`char4`, `ascii_text`, `utf8_text`. + +## Front-end self-hosted + +Diferente de implementações que só compilam em C, aqui o **lexer, o +parser, o checker e o compiler são programas catscript**: + +- `src/catscript/lexer.cat` — tokeniza o fonte. +- `src/catscript/parser.cat` — constrói a AST. +- `src/catscript/checker.cat` — checagem estrutural (diagnósticos). +- `src/catscript/compiler.cat` — gera bytecode a partir da AST. + +O runtime C expõe primitivas (`bc_run`, `bc_dump`) que transformam uma +"chunk" (uma tabela catscript: `{name, nparams, nlocals, consts, protos, +code}`) em bytecode executável. Assim, código catscript compila e executa +código catscript. + +Veja `tests/selfhost_compile.cat`: dado um fonte, o pipeline +lexer→parser→checker→compiler (todo em catscript) produz bytecode que +roda de verdade. + +## Type hints + +Type hints são suportados e **advisory** (a tipagem é estrutural em +runtime): + +```lua +local a : int = 10 +function add(x : int, y : int) -> int + return x + y +end +``` + +## Concorrência: multithreading sem GIL + +Não há GIL nem qualquer lock global. Cada `CAT_VM_State` é +autocontido (globais, nativos e pilha próprios), e o "VM atual" usado +por closures/nativos é `_Thread_local`. Duas VMs podem executar em +threads distintas sem interferência nem coordenação. + +As funções nativas são **valores de primeira classe** (`native`), +armazenáveis em globais, atributos e métodos de classe — por isso o +registro de nativos é por-VM, não global. + +## A família de arquivos + +`AbstractFile` é a **classe abstrata** base de todo stream de bytes; +as concretas compartilham seu conjunto de métodos (`read`/`write`/ +`close`/`name`), então são intercambiáveis: + +```lua +local s = StringIO("hello") -- stream de texto em memória +local b = BytesIO() -- stream de bytes em memória +b:write("bytes"); print(b:read()) + +local f = File::open("x.txt") -- classmethod -> File +f:write("data"); f:close() + +local r = File::open("x.txt", "r") +print(r:read()); r:close() +``` + +`File::open(path[, mode])` é um **classmethod** (sintaxe `::`) que +retorna um `File`. `AbstractFile` não é instanciável. + +## Class methods (`::`) + +Chamadas com `::` passam o receptor como primeiro argumento (`self`), +como `Object::method(args)` em outras linguagens: + +```lua +local f = File::open("a.txt") -- File::open +``` + +## Type hints avançados + +Type hints continuam **advisory** (tipagem estrutural em runtime), mas o +parser aceita tipos completos, incluindo tamanhos conhecidos apenas em +tempo de compilação via `DynSized()` e sentinelas: + +```lua +function main(argc: cint, + argv: cbyte[sentinel_sized<0>][argc]) -> cint + return 0 +end +``` + +`cint`, `cbyte` são os tipos C; `DynSized()` marca tipos cujo tamanho só +se conhece na compilação; `sentinel_sized<'\0'>` marca arrays terminados +por um valor sentinela. + +## cpk — Cat Package Manager + +O primeiro programa em catscript. Lê o `package.toml` de um pacote +(todo pacote tem um) com o parser TOML da biblioteca padrão: + +```sh +catscript examples/cpk.cat show examples/package.toml +# package: hello-world +# version: 0.1.0 +# author: Minus +``` + +## Biblioteca padrão + +Instalada em toda VM: `print`, `tostring`, `tonumber`, `type`, `len`, +`read_file`, `write_file`, `ord`, `chr`, `substr`, `dofile`, **TOML** +(`toml_parse`, `toml_encode`), e as **classes de arquivo** +(`AbstractFile`, `File`, `StringIO`, `BytesIO`). O TOML faz parte da +biblioteca padrão, como requerido. + +## Convenção de nomes + +Os nomes codificam o caminho do arquivo no projeto (`/` → `_`): + +- uma função em `a/b/c.h` chama-se `a_b_c_funcao()`; +- um tipo lá chama-se `A_B_C_MeuTipo`. + +O diretório raiz (`include/` ou `src/`) não entra no nome, então +`include/cat/types/int.h` e `src/cat/types/int.c` são ambos o módulo +`cat_types_int`. + +## Estrutura + +``` +include/cat/ C API (value, vm, bytecode, compiler, lexer, module, stdlib, types) +src/cat/ implementação C (modelo de objetos, VM, stdlib, TOML) +src/catscript/ front-end self-hosted (lexer/parser/checker/compiler em .cat) +src/main.c CLI (run / --dump / --help / REPL) +examples/ programas de exemplo + cpk + package.toml +tests/ suíte automatizada + testes self-hosted +``` diff --git a/examples/arith.cat b/examples/arith.cat new file mode 100644 index 0000000..a1a403e --- /dev/null +++ b/examples/arith.cat @@ -0,0 +1,14 @@ +-- examples/arith.cat -- arithmetic over int, float and byte. +-- Type hints (`: int`) are advisory: catscript is structurally typed. + +local a : int = 10 +local b : int = 3 +print("a + b =", a + b) -- 13 +print("a - b =", a - b) -- 7 +print("a * b =", a * b) -- 30 +print("a / b =", a / b) -- 3.33333 (division yields float) +print("a % b =", a % b) -- 1 + +local x : float = 1.5 +print("x + b =", x + b) -- 4.5 +print("x * 2 =", x * 2) -- 3 diff --git a/examples/control.cat b/examples/control.cat new file mode 100644 index 0000000..fff93a6 --- /dev/null +++ b/examples/control.cat @@ -0,0 +1,29 @@ +-- examples/control.cat -- if/elseif/else, while and numeric for. + +function classify(n) + if n < 0 then + return "negative" + elseif n == 0 then + return "zero" + else + return "positive" + end +end + +print(classify(-5)) -- negative +print(classify(0)) -- zero +print(classify(42)) -- positive + +local sum = 0 +local i = 1 +while i <= 5 do + sum = sum + i + i = i + 1 +end +print("sum 1..5 =", sum) -- 15 + +local acc = 0 +for j = 1, 4 do + acc = acc + j +end +print("sum 1..4 =", acc) -- 10 diff --git a/examples/cpk.cat b/examples/cpk.cat new file mode 100644 index 0000000..fc3a296 --- /dev/null +++ b/examples/cpk.cat @@ -0,0 +1,54 @@ +-- examples/cpk.cat -- cpk, the Cat Package Manager. +-- +-- This is the first real program written in catscript. cpk reads a +-- package's `package.toml` manifest (every package has one) using the +-- standard library's TOML parser. Commands: +-- +-- cpk show [file.toml] -- parse and print a manifest (default: package.toml) +-- cpk new -- print a starter manifest +-- +-- Run: catscript examples/cpk.cat show examples/package.toml + +function cpk_show(path) + local text = read_file(path) + if text == nil then + print("cpk: cannot read " .. path) + return 1 + end + local pkg = toml_parse(text) + print("package: " .. tostring(pkg.name)) + print("version: " .. tostring(pkg.version)) + print("author: " .. tostring(pkg.author)) + return 0 +end + +function cpk_new(name) + print("# package.toml for " .. name) + print("name = \"" .. name .. "\"") + print("version = \"0.1.0\"") + print("author = \"\"") + return 0 +end + +function cpk_usage() + print("cpk -- cat package manager") + print("usage: cpk show [file.toml] | cpk new ") + return 0 +end + +function cpk_main(argv) + local cmd = argv[1] + if cmd == "show" then + local path = argv[2] + if path == nil then + path = "package.toml" + end + return cpk_show(path) + elseif cmd == "new" then + return cpk_new(argv[2]) + else + return cpk_usage() + end +end + +cpk_main({ "show", "examples/package.toml" }) diff --git a/examples/files.cat b/examples/files.cat new file mode 100644 index 0000000..9597ed6 --- /dev/null +++ b/examples/files.cat @@ -0,0 +1,31 @@ +-- examples/files.cat -- the file family and classmethods. +-- +-- AbstractFile is the abstract base; File, StringIO and BytesIO share +-- its method set (read/write/close), so they are interchangeable. +-- `File::open(path)` is a classmethod producing a File value. + +-- in-memory text stream +local s = StringIO("hello, catscript") +print("stringio:", s:read()) + +-- in-memory byte stream, written then read back +local b = BytesIO() +b:write("bytes ") +b:write("io") +print("bytesio:", b:read()) + +-- a real file, opened with the File::open classmethod +local path = "/tmp/catscript_demo.txt" +local w = File::open(path, "w") +w:write("line one\n") +w:close() + +local r = File::open(path, "r") +print("file:", r:read()) +r:close() + +-- type hints: advisory, including DynSized() and sentinel_sized +function describe(n : cint, buf : cbyte[sentinel_sized<0>]) -> ascii_text + return "n=" .. tostring(n) .. " buf=" .. tostring(buf) +end +print(describe(3, "abc")) diff --git a/examples/hello.cat b/examples/hello.cat new file mode 100644 index 0000000..e954516 --- /dev/null +++ b/examples/hello.cat @@ -0,0 +1,5 @@ +-- examples/hello.cat -- the smallest catscript program. +-- Run: catscript examples/hello.cat + +print("hello from catscript") +print("2 + 3 =", 2 + 3) diff --git a/examples/oop.cat b/examples/oop.cat new file mode 100644 index 0000000..b4c54db --- /dev/null +++ b/examples/oop.cat @@ -0,0 +1,18 @@ +-- examples/oop.cat -- tables as objects, with methods. +-- catscript is 100% object-oriented: a method is just a function value +-- stored in a table, called with `:`. + +local counter = { + value = 0, + increment = function(self, by) + self.value = self.value + by + return self.value + end, + get = function(self) + return self.value + end +} + +counter:increment(1) +counter:increment(2) +print("counter:", counter:get()) -- 3 diff --git a/examples/package.toml b/examples/package.toml new file mode 100644 index 0000000..5f58717 --- /dev/null +++ b/examples/package.toml @@ -0,0 +1,9 @@ +# package.toml -- manifest for a catscript package. +# This is the file cpk reads: every package has a `package.toml`. +name = "hello-world" +version = "0.1.0" +author = "Minus" +description = "an example catscript package" + +[dependencies] +toml = "1.0.0" diff --git a/examples/text.cat b/examples/text.cat new file mode 100644 index 0000000..867cbae --- /dev/null +++ b/examples/text.cat @@ -0,0 +1,10 @@ +-- examples/text.cat -- text values, concatenation and `length`. +-- ascii_text / utf8_text are Cat_Text; `#x` reads the length attribute. + +local name : ascii_text = "cat" +local greeting = "hello, " .. name +print(greeting) -- hello, cat +print("length:", #greeting) -- 11 + +local u : utf8_text = "café" +print("utf8 length:", u.length) -- 4 code points diff --git a/examples/toml.cat b/examples/toml.cat new file mode 100644 index 0000000..2d616f7 --- /dev/null +++ b/examples/toml.cat @@ -0,0 +1,7 @@ +-- examples/toml.cat -- the standard library TOML parser in action. + +local doc = toml_parse("title = \"catscript\"\nversion = 1\npi = 3.14\n") + +print("title:", doc.title) +print("version:", doc.version) +print("pi:", doc.pi) diff --git a/include/cat/bytecode.h b/include/cat/bytecode.h new file mode 100644 index 0000000..9fdc9e9 --- /dev/null +++ b/include/cat/bytecode.h @@ -0,0 +1,110 @@ +/* + * cat/bytecode.h -- the catscript bytecode format. + * + * Naming rule: symbols here are cat_bytecode_* / CAT_BYTECODE_*. + * + * A compiled module is one CAT_BYTECODE_Function. Instructions are a + * flat array of CAT_BYTECODE_Instr. The VM (cat/vm.h) executes them. + * + * Operand conventions: + * - A/B/C are small integer operands (register-free, stack based). + * - constants live in `consts[]`; locals in the current frame;s slots. + */ +#ifndef CAT_BYTECODE_H +#define CAT_BYTECODE_H + +#include "cat/value.h" +#include + +/* Opcodes (documented, stable). */ +enum CAT_BYTECODE_Op { + CAT_BYTECODE_OP_NOP = 0, + CAT_BYTECODE_OP_CONST, /* A: index into consts[] */ + CAT_BYTECODE_OP_NIL, /* push nil */ + CAT_BYTECODE_OP_TRUE, /* push true */ + CAT_BYTECODE_OP_FALSE, /* push false */ + CAT_BYTECODE_OP_GETLOCAL, /* A: local slot -> stack */ + CAT_BYTECODE_OP_SETLOCAL, /* A: pop -> local slot */ + CAT_BYTECODE_OP_GETGLOBAL, /* A: const name -> stack */ + CAT_BYTECODE_OP_SETGLOBAL, /* A: const name, pop value */ + CAT_BYTECODE_OP_ADD, /* pop b, a -> push a+b */ + CAT_BYTECODE_OP_SUB, + CAT_BYTECODE_OP_MUL, + CAT_BYTECODE_OP_DIV, + CAT_BYTECODE_OP_REM, + CAT_BYTECODE_OP_NEG, /* unary minus */ + CAT_BYTECODE_OP_NOT, + CAT_BYTECODE_OP_EQ, + CAT_BYTECODE_OP_NE, + CAT_BYTECODE_OP_LT, + CAT_BYTECODE_OP_LE, + CAT_BYTECODE_OP_GT, + CAT_BYTECODE_OP_GE, + CAT_BYTECODE_OP_GETATTR, /* A: const name; pop obj -> stack */ + CAT_BYTECODE_OP_SETATTR, /* A: const name; pop val, obj */ + CAT_BYTECODE_OP_NEWTABLE, /* push empty table */ + CAT_BYTECODE_OP_CALL, /* A: nargs; pop fn+args */ + CAT_BYTECODE_OP_CALLMETHOD, /* A: nargs; B: const name */ + CAT_BYTECODE_OP_JUMP, /* A: absolute target */ + CAT_BYTECODE_OP_JUMPIF, /* A: target; pop cond */ + CAT_BYTECODE_OP_JUMPIFNOT, /* A: target; pop cond */ + CAT_BYTECODE_OP_RETURN, /* pop -> return */ + CAT_BYTECODE_OP_RETURN0, /* return nil */ + CAT_BYTECODE_OP_POP, /* discard top */ + CAT_BYTECODE_OP_PRINT, /* pop, print */ + CAT_BYTECODE_OP_CLOSURE, /* A: index into protos[] */ + CAT_BYTECODE_OP_GETUPVAL, /* A: upvalue slot */ + CAT_BYTECODE_OP_CONCAT, /* string concat fast path */ + CAT_BYTECODE_OP_DUP, /* duplicate top of stack */ + CAT_BYTECODE_OP_GETIDX, /* pop idx, obj -> push obj[idx] */ + CAT_BYTECODE_OP_SETIDX, /* pop val, idx, obj -> obj[idx]=val */ +}; + +/* One instruction: opcode + three integer operands. */ +typedef struct CAT_BYTECODE_Instr { + unsigned char op; /* a CAT_BYTECODE_Op */ + int a; + int b; + int c; + int line; /* source line for diagnostics */ +} CAT_BYTECODE_Instr; + +struct CAT_BYTECODE_Function; + +/* A constant pool entry: a value plus (for names) a string. */ +typedef struct CAT_BYTECODE_Constant { + CAT_VALUE_Value *value; +} CAT_BYTECODE_Constant; + +/* CAT_BYTECODE_Function -- a compiled chunk. + * `protos` holds nested function prototypes (for `function` literals). */ +typedef struct CAT_BYTECODE_Function { + char *name; + CAT_BYTECODE_Instr *code; + int ncode, capcode; + CAT_BYTECODE_Constant *consts; + int nconsts, capconsts; + struct CAT_BYTECODE_Function **protos; + int nprotos, capprotos; + int nlocals; /* number of local slots */ + int nparams; /* number of parameters */ +} CAT_BYTECODE_Function; + +CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name); + +/* Emit one instruction, returning its index. */ +int cat_bytecode_emit(CAT_BYTECODE_Function *fn, unsigned char op, + int a, int b, int c, int line); + +/* Add a constant; returns its index. */ +int cat_bytecode_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v); + +/* Add a nested prototype; returns its index. */ +int cat_bytecode_add_proto(CAT_BYTECODE_Function *fn, CAT_BYTECODE_Function *p); + +/* Human-readable disassembly (used by `--dump`). */ +void cat_bytecode_dump(CAT_BYTECODE_Function *fn, FILE *out); + +void cat_bytecode_function_free(CAT_BYTECODE_Function *fn); + +#endif /* CAT_BYTECODE_H */ diff --git a/include/cat/compiler.h b/include/cat/compiler.h new file mode 100644 index 0000000..8f96c67 --- /dev/null +++ b/include/cat/compiler.h @@ -0,0 +1,20 @@ +/* + * cat/compiler.h -- source -> bytecode compiler. + * + * Naming rule: symbols here are cat_compiler_* / CAT_COMPILER_*. + * + * The compiler is a recursive-descent parser over the Lua-like syntax. + * It performs structural-typing checks only where cheap (nothing is + * nominal) and accepts optional `: type` hints, which are advisory. + */ +#ifndef CAT_COMPILER_H +#define CAT_COMPILER_H + +#include "cat/bytecode.h" +#include "cat/error.h" + +/* Compile `source` into a fresh top-level function. */ +CAT_BYTECODE_Function *cat_compiler_compile(const char *source, + CAT_ERROR_Error *err); + +#endif /* CAT_COMPILER_H */ diff --git a/include/cat/error.h b/include/cat/error.h new file mode 100644 index 0000000..ba15b7d --- /dev/null +++ b/include/cat/error.h @@ -0,0 +1,29 @@ +/* + * cat/error.h -- runtime error object. + * + * Naming rule: a symbol living in `cat/error.h` (path without the + * leading include/ or src/ prefix) is named cat_error_* / CAT_ERROR_*. + * + * Catscript runtime errors are carried in a plain value struct so that + * any C-API call can report failure without exceptions or longjmp. + */ +#ifndef CAT_ERROR_H +#define CAT_ERROR_H + +#include + +/* CAT_ERROR_Error -- an error slot passed into API calls. */ +/* `raised` becomes true when an operation fails; `message` is a */ +/* human-readable description (always NUL terminated when raised). */ +typedef struct CAT_ERROR_Error { + bool raised; + char message[256]; +} CAT_ERROR_Error; + +/* Clear an error slot back to the "no error" state. */ +void cat_error_clear(CAT_ERROR_Error *err); + +/* Raise (fill) an error slot with a printf-style message. */ +void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...); + +#endif /* CAT_ERROR_H */ diff --git a/include/cat/lexer.h b/include/cat/lexer.h new file mode 100644 index 0000000..ee91eef --- /dev/null +++ b/include/cat/lexer.h @@ -0,0 +1,66 @@ +/* + * cat/lexer.h -- tokenizer for catscript source. + * + * Naming rule: symbols here are cat_lexer_* / CAT_LEXER_*. + * + * The lexer turns Lua-like source into a stream of CAT_LEXER_Token. + * Keywords follow Lua; type hints use `:` in a few documented spots. + */ +#ifndef CAT_LEXER_H +#define CAT_LEXER_H + +#include + +/* Token kinds. */ +enum CAT_LEXER_Kind { + CAT_LEXER_TOK_EOF = 0, + CAT_LEXER_TOK_NAME, + CAT_LEXER_TOK_INT, + CAT_LEXER_TOK_FLOAT, + CAT_LEXER_TOK_STRING, + /* keywords */ + CAT_LEXER_TOK_AND, CAT_LEXER_TOK_BREAK, CAT_LEXER_TOK_DO, + CAT_LEXER_TOK_ELSE, CAT_LEXER_TOK_ELSEIF, CAT_LEXER_TOK_END, + CAT_LEXER_TOK_FALSE, CAT_LEXER_TOK_FOR, CAT_LEXER_TOK_FUNCTION, + CAT_LEXER_TOK_IF, CAT_LEXER_TOK_IN, CAT_LEXER_TOK_LOCAL, + CAT_LEXER_TOK_NIL, CAT_LEXER_TOK_NOT, CAT_LEXER_TOK_OR, + CAT_LEXER_TOK_REPEAT, CAT_LEXER_TOK_RETURN, CAT_LEXER_TOK_THEN, + CAT_LEXER_TOK_TRUE, CAT_LEXER_TOK_UNTIL, CAT_LEXER_TOK_WHILE, + /* 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, + CAT_LEXER_TOK_HASH, CAT_LEXER_TOK_EQ, CAT_LEXER_TOK_NE, + CAT_LEXER_TOK_LE, CAT_LEXER_TOK_GE, CAT_LEXER_TOK_LT, + CAT_LEXER_TOK_GT, CAT_LEXER_TOK_ASSIGN, CAT_LEXER_TOK_LPAREN, + CAT_LEXER_TOK_RPAREN, CAT_LEXER_TOK_LBRACE, CAT_LEXER_TOK_RBRACE, + CAT_LEXER_TOK_LBRACKET, CAT_LEXER_TOK_RBRACKET, + CAT_LEXER_TOK_SEMI, CAT_LEXER_TOK_COMMA, CAT_LEXER_TOK_DOT, + CAT_LEXER_TOK_COLON, CAT_LEXER_TOK_DCOLON, CAT_LEXER_TOK_CONCAT, + CAT_LEXER_TOK_ARROW +}; + +/* A lexed token: kind + payload + source line. */ +typedef struct CAT_LEXER_Token { + int kind; + char text[256]; /* NAME / STRING payload */ + long long ival; /* INT payload */ + double fval; /* FLOAT payload */ + int line; +} CAT_LEXER_Token; + +/* CAT_LEXER_Lexer -- cursor over a source buffer. */ +typedef struct CAT_LEXER_Lexer { + const char *src; + size_t pos; + int line; +} CAT_LEXER_Lexer; + +void cat_lexer_init(CAT_LEXER_Lexer *lx, const char *src); + +/* Produce the next token into *out; returns 0 on success. */ +int cat_lexer_next(CAT_LEXER_Lexer *lx, CAT_LEXER_Token *out); + +/* Peek-friendly variant used by the parser: one-token lookahead. */ +const char *cat_lexer_kind_name(int kind); + +#endif /* CAT_LEXER_H */ diff --git a/include/cat/module.h b/include/cat/module.h new file mode 100644 index 0000000..20fcab8 --- /dev/null +++ b/include/cat/module.h @@ -0,0 +1,39 @@ +/* + * cat/module.h -- Cat_Module, a unit of catscript code. + * + * Naming rule: symbols declared here are cat_module_* / CAT_MODULE_*. + * (Path of this header below include/ is `cat/module`, so cat_module_*.) + * + * A module owns a name and a compiled entry prototype. Loading a module + * is how an embedder turns catscript source into something callable. + */ +#ifndef CAT_MODULE_H +#define CAT_MODULE_H + +#include "cat/value.h" +#include "cat/error.h" + +struct CAT_BYTECODE_Function; + +/* CAT_MODULE_Module == Cat_Module. + * One compilable unit: a name plus its top-level function prototype. */ +typedef struct CAT_MODULE_Module { + char *name; + struct CAT_BYTECODE_Function *main; +} CAT_MODULE_Module; + +/* Create an empty module with the given name (name is copied). */ +CAT_MODULE_Module *cat_module_new(const char *name); + +/* Compile catscript source text into this module. */ +int cat_module_compile(CAT_MODULE_Module *mod, const char *source, + CAT_ERROR_Error *err); + +/* Execute the module's main prototype; `out` receives its return value. */ +int cat_module_run(CAT_MODULE_Module *mod, CAT_VALUE_Value **out, + CAT_ERROR_Error *err); + +/* Free a module. */ +void cat_module_free(CAT_MODULE_Module *mod); + +#endif /* CAT_MODULE_H */ diff --git a/include/cat/stdlib/build.h b/include/cat/stdlib/build.h new file mode 100644 index 0000000..7685a5a --- /dev/null +++ b/include/cat/stdlib/build.h @@ -0,0 +1,25 @@ +/* + * cat/stdlib/build.h -- bytecode builder primitives for self-hosted tools. + * + * Naming rule: symbols here are cat_stdlib_build_* / CAT_STDLIB_BUILD_*. + * + * The lexer/parser/checker/compiler are written in catscript itself. To + * let them produce bytecode, a compiled chunk is represented as plain + * catscript data (a table) and this module turns that data into a real + * CAT_BYTECODE_Function the VM can run. + * + * A chunk table has the shape: + * { name=..., nparams=N, nlocals=N, + * consts={ v0, v1, ... }, -- constant pool (any values) + * protos={ chunk0, chunk1, ... }, -- nested chunk tables + * code={ {op=1,a=0,b=0,c=0,line=1}, ... } } + */ +#ifndef CAT_STDLIB_BUILD_H +#define CAT_STDLIB_BUILD_H + +#include "cat/vm.h" + +/* Install the builder natives (bc_run, bc_dump) into `vm`. */ +int cat_stdlib_build_install(CAT_VM_State *vm); + +#endif /* CAT_STDLIB_BUILD_H */ diff --git a/include/cat/stdlib/stdlib.h b/include/cat/stdlib/stdlib.h new file mode 100644 index 0000000..b576a96 --- /dev/null +++ b/include/cat/stdlib/stdlib.h @@ -0,0 +1,18 @@ +/* + * cat/stdlib/stdlib.h -- the catscript standard library bindings. + * + * Naming rule: symbols here are cat_stdlib_stdlib_* / CAT_STDLIB_STDLIB_*. + * + * The stdlib is exposed to catscript as native functions installed into + * a VM's globals. It is also part of the C API: an embedder may call + * these helpers directly. + */ +#ifndef CAT_STDLIB_STDLIB_H +#define CAT_STDLIB_STDLIB_H + +#include "cat/vm.h" + +/* Install the whole standard library into `vm`'s globals. */ +int cat_stdlib_stdlib_install(CAT_VM_State *vm); + +#endif /* CAT_STDLIB_STDLIB_H */ diff --git a/include/cat/stdlib/toml.h b/include/cat/stdlib/toml.h new file mode 100644 index 0000000..cd5b473 --- /dev/null +++ b/include/cat/stdlib/toml.h @@ -0,0 +1,25 @@ +/* + * cat/stdlib/toml.h -- TOML parsing/encoding for the standard library. + * + * Naming rule: symbols here are cat_stdlib_toml_* / CAT_STDLIB_TOML_*. + * + * The parser supports the commonly used TOML subset: key/value pairs, + * [tables], [[array-of-tables]], strings, integers, floats, booleans, + * and inline arrays. It produces a CAT_TYPES_TABLE_Table value, so TOML + * documents are just objects to catscript. This is intentionally a + * focused subset, documented in the README. + */ +#ifndef CAT_STDLIB_TOML_H +#define CAT_STDLIB_TOML_H + +#include "cat/value.h" +#include "cat/error.h" + +/* Parse `text` as TOML; on success *out is a table value. */ +int cat_stdlib_toml_parse(const char *text, CAT_VALUE_Value **out, + CAT_ERROR_Error *err); + +/* Serialize a table value back to TOML text (heap string, caller frees). */ +char *cat_stdlib_toml_encode(CAT_VALUE_Value *tbl, CAT_ERROR_Error *err); + +#endif /* CAT_STDLIB_TOML_H */ diff --git a/include/cat/types/ascii_text.h b/include/cat/types/ascii_text.h new file mode 100644 index 0000000..0392c1f --- /dev/null +++ b/include/cat/types/ascii_text.h @@ -0,0 +1,21 @@ +/* + * cat/types/ascii_text.h -- the concrete `ascii_text` type. + * + * Naming rule: symbols here are cat_types_ascii_text_*. + * A heap-owned, NUL-terminated ASCII string; a Cat_Text. + */ +#ifndef CAT_TYPES_ASCII_TEXT_H +#define CAT_TYPES_ASCII_TEXT_H + +#include "cat/types/text.h" + +/* CAT_TYPES_ASCII_TEXT_AsciiText -- concrete ASCII text value. */ +typedef struct CAT_TYPES_ASCII_TEXT_AsciiText { + CAT_TYPES_TEXT_Text text; /* base (must be first) */ + char *owned; /* heap storage of `len`+1 bytes */ +} CAT_TYPES_ASCII_TEXT_AsciiText; + +CAT_VALUE_Value *cat_types_ascii_text_new(const char *s); +CAT_VALUE_Vtable *cat_types_ascii_text_vtable(void); + +#endif /* CAT_TYPES_ASCII_TEXT_H */ diff --git a/include/cat/types/bool.h b/include/cat/types/bool.h new file mode 100644 index 0000000..cc19361 --- /dev/null +++ b/include/cat/types/bool.h @@ -0,0 +1,21 @@ +/* + * cat/types/bool.h -- the boolean type. + * + * Naming rule: symbols here are cat_types_bool_* / CAT_TYPES_BOOL_*. + */ +#ifndef CAT_TYPES_BOOL_H +#define CAT_TYPES_BOOL_H + +#include "cat/value.h" + +typedef struct CAT_TYPES_BOOL_Bool { + CAT_VALUE_Value base; + int v; /* 0 or 1 */ +} CAT_TYPES_BOOL_Bool; + +/* Shared singletons for true/false. */ +CAT_VALUE_Value *cat_types_bool_true(void); +CAT_VALUE_Value *cat_types_bool_false(void); +CAT_VALUE_Vtable *cat_types_bool_vtable(void); + +#endif /* CAT_TYPES_BOOL_H */ diff --git a/include/cat/types/byte.h b/include/cat/types/byte.h new file mode 100644 index 0000000..3303d77 --- /dev/null +++ b/include/cat/types/byte.h @@ -0,0 +1,21 @@ +/* + * cat/types/byte.h -- the concrete `byte` type. + * + * Naming rule: symbols here are cat_types_byte_* / CAT_TYPES_BYTE_*. + * `byte` is an unsigned 8-bit number; it participates in arithmetic as + * an integral Cat_Number and wraps at 256 when stored back. + */ +#ifndef CAT_TYPES_BYTE_H +#define CAT_TYPES_BYTE_H + +#include "cat/types/number.h" + +/* CAT_TYPES_BYTE_Byte -- concrete 8-bit unsigned number. */ +typedef struct CAT_TYPES_BYTE_Byte { + CAT_TYPES_NUMBER_Number number; /* base (must be first) */ +} CAT_TYPES_BYTE_Byte; + +CAT_VALUE_Value *cat_types_byte_new(unsigned int v); +CAT_VALUE_Vtable *cat_types_byte_vtable(void); + +#endif /* CAT_TYPES_BYTE_H */ diff --git a/include/cat/types/char.h b/include/cat/types/char.h new file mode 100644 index 0000000..5110509 --- /dev/null +++ b/include/cat/types/char.h @@ -0,0 +1,25 @@ +/* + * cat/types/char.h -- the fixed-width text types char1..char4 (Cat_Text). + * + * Naming rule: symbols here are cat_types_char_* / CAT_TYPES_CHAR_*. + * Each charN holds exactly N bytes; the width is part of the type name. + */ +#ifndef CAT_TYPES_CHAR_H +#define CAT_TYPES_CHAR_H + +#include "cat/types/text.h" + +/* CAT_TYPES_CHAR_Char -- concrete fixed-width text. `width` is 1..4. */ +typedef struct CAT_TYPES_CHAR_Char { + CAT_TYPES_TEXT_Text text; /* base (must be first) */ + int width; /* 1, 2, 3 or 4 */ + char buf[5]; /* storage, NUL padded */ +} CAT_TYPES_CHAR_Char; + +/* Create a charN value (width 1..4); `s` is truncated/NUL-padded. */ +CAT_VALUE_Value *cat_types_char_new(int width, const char *s); + +/* Vtable selector for each width. */ +CAT_VALUE_Vtable *cat_types_char_vtable(int width); + +#endif /* CAT_TYPES_CHAR_H */ diff --git a/include/cat/types/file.h b/include/cat/types/file.h new file mode 100644 index 0000000..52437b1 --- /dev/null +++ b/include/cat/types/file.h @@ -0,0 +1,64 @@ +/* + * cat/types/file.h -- the file family. + * + * Naming rule: symbols here are cat_types_file_* / CAT_TYPES_FILE_*. + * + * AbstractFile is the abstract base for every byte stream. Concrete + * subclasses share the same method set (read/write/close/name) through + * the base vtable, so they are interchangeable: + * + * AbstractFile -- abstract base: read/write/close/name + * File -- a real filesystem file; constructed by File::open() + * StringIO -- an in-memory text buffer (read as text) + * BytesIO -- an in-memory byte buffer (read as bytes) + * + * `File` is also exposed to catscript as a class table so that + * `File::open(path)` / `File:open(path)` produce a `File` value. + */ +#ifndef CAT_TYPES_FILE_H +#define CAT_TYPES_FILE_H + +#include "cat/value.h" + +/* How a stream was opened. */ +enum { + CAT_TYPES_FILE_MODE_READ = 1, + CAT_TYPES_FILE_MODE_WRITE = 2, + CAT_TYPES_FILE_MODE_APPEND = 4 +}; + +/* CAT_TYPES_FILE_AbstractFile -- common header for every stream. */ +typedef struct CAT_TYPES_FILE_AbstractFile { + CAT_VALUE_Value base; /* vtable header (must be first) */ + int mode; /* CAT_TYPES_FILE_MODE_* */ + int closed; + int is_bytes; /* StringIO:0, BytesIO:1 */ +} CAT_TYPES_FILE_AbstractFile; + +/* A real file stream. */ +typedef struct CAT_TYPES_FILE_File { + CAT_TYPES_FILE_AbstractFile af; + void *fp; /* FILE * (kept opaque here) */ + char *path; +} CAT_TYPES_FILE_File; + +/* An in-memory stream (StringIO/BytesIO). */ +typedef struct CAT_TYPES_FILE_MemFile { + CAT_TYPES_FILE_AbstractFile af; + char *buf; + long len, cap, pos; +} CAT_TYPES_FILE_MemFile; + +/* Constructors. */ +CAT_VALUE_Value *cat_types_file_open(const char *path, const char *mode); +CAT_VALUE_Value *cat_types_file_stringio(const char *initial); +CAT_VALUE_Value *cat_types_file_bytesio(void); + +/* The abstract base vtable (all streams share its methods). */ +CAT_VALUE_Vtable *cat_types_file_abstract_vtable(void); + +/* Build the `File` class table (with the `open` classmethod) into a new + * value; used by the stdlib to expose `File`/`AbstractFile`/`StringIO`/`BytesIO`. */ +CAT_VALUE_Value *cat_types_file_class_table(void); + +#endif /* CAT_TYPES_FILE_H */ diff --git a/include/cat/types/float.h b/include/cat/types/float.h new file mode 100644 index 0000000..d6d3f5d --- /dev/null +++ b/include/cat/types/float.h @@ -0,0 +1,20 @@ +/* + * cat/types/float.h -- the concrete `float` type. + * + * Naming rule: symbols here are cat_types_float_* / CAT_TYPES_FLOAT_*. + * `float` is a Cat_Number (floating point). + */ +#ifndef CAT_TYPES_FLOAT_H +#define CAT_TYPES_FLOAT_H + +#include "cat/types/number.h" + +/* CAT_TYPES_FLOAT_Float -- concrete floating point number. */ +typedef struct CAT_TYPES_FLOAT_Float { + CAT_TYPES_NUMBER_Number number; /* base (must be first) */ +} CAT_TYPES_FLOAT_Float; + +CAT_VALUE_Value *cat_types_float_new(double v); +CAT_VALUE_Vtable *cat_types_float_vtable(void); + +#endif /* CAT_TYPES_FLOAT_H */ diff --git a/include/cat/types/function.h b/include/cat/types/function.h new file mode 100644 index 0000000..be31613 --- /dev/null +++ b/include/cat/types/function.h @@ -0,0 +1,27 @@ +/* + * cat/types/function.h -- closures (Cat_ImplementsCall). + * + * Naming rule: symbols here are cat_types_function_*. + */ +#ifndef CAT_TYPES_FUNCTION_H +#define CAT_TYPES_FUNCTION_H + +#include "cat/value.h" +#include "cat/bytecode.h" + +struct CAT_VM_State; + +/* CAT_TYPES_FUNCTION_Closure -- prototype + captured upvalues. */ +typedef struct CAT_TYPES_FUNCTION_Closure { + CAT_VALUE_Value base; + struct CAT_BYTECODE_Function *proto; + CAT_VALUE_Value **upvals; /* captured values */ + int nupvals; +} CAT_TYPES_FUNCTION_Closure; + +/* Wrap a prototype as a callable closure. */ +CAT_VALUE_Value *cat_types_function_new(struct CAT_BYTECODE_Function *proto); + +CAT_VALUE_Vtable *cat_types_function_vtable(void); + +#endif /* CAT_TYPES_FUNCTION_H */ diff --git a/include/cat/types/int.h b/include/cat/types/int.h new file mode 100644 index 0000000..fd21967 --- /dev/null +++ b/include/cat/types/int.h @@ -0,0 +1,23 @@ +/* + * cat/types/int.h -- the concrete `int` type. + * + * Naming rule: symbols here are cat_types_int_* / CAT_TYPES_INT_*. + * `int` is a Cat_Number (integral). + */ +#ifndef CAT_TYPES_INT_H +#define CAT_TYPES_INT_H + +#include "cat/types/number.h" + +/* CAT_TYPES_INT_Int -- concrete integral number. */ +typedef struct CAT_TYPES_INT_Int { + CAT_TYPES_NUMBER_Number number; /* base (must be first) */ +} CAT_TYPES_INT_Int; + +/* Allocate an int value. */ +CAT_VALUE_Value *cat_types_int_new(long long v); + +/* Shared int vtable (exposed for the compiler's constant folding). */ +CAT_VALUE_Vtable *cat_types_int_vtable(void); + +#endif /* CAT_TYPES_INT_H */ diff --git a/include/cat/types/native.h b/include/cat/types/native.h new file mode 100644 index 0000000..215d67d --- /dev/null +++ b/include/cat/types/native.h @@ -0,0 +1,35 @@ +/* + * cat/types/native.h -- native (C-implemented) functions as values. + * + * Naming rule: symbols here are cat_types_native_* / CAT_TYPES_NATIVE_*. + * + * A native function is a first-class value (Cat_ImplementsCall) backed by + * a C callback. Making natives ordinary values means they can be stored + * anywhere -- globals, table attributes, class methods -- and the VM + * dispatches them through the same cat_value_call path as closures, with + * no process-global registry. + */ +#ifndef CAT_TYPES_NATIVE_H +#define CAT_TYPES_NATIVE_H + +#include "cat/value.h" + +/* Forward declaration matching cat/vm.h. */ +typedef struct CAT_VM_State CAT_VM_State; + +/* CAT_TYPES_NATIVE_Native -- a C callback wrapped as a callable value. */ +typedef struct CAT_TYPES_NATIVE_Native { + CAT_VALUE_Value base; + char *name; + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); +} CAT_TYPES_NATIVE_Native; + +CAT_VALUE_Value *cat_types_native_new(const char *name, + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **)); + +CAT_VALUE_Vtable *cat_types_native_vtable(void); + +/* True if v is a native function value. */ +int cat_types_native_is(CAT_VALUE_Value *v); + +#endif /* CAT_TYPES_NATIVE_H */ diff --git a/include/cat/types/nil.h b/include/cat/types/nil.h new file mode 100644 index 0000000..54be273 --- /dev/null +++ b/include/cat/types/nil.h @@ -0,0 +1,20 @@ +/* + * cat/types/nil.h -- the `nil` singleton value. + * + * Naming rule: symbols here are cat_types_nil_* / CAT_TYPES_NIL_*. + * `nil` is falsy and participates in no arithmetic. + */ +#ifndef CAT_TYPES_NIL_H +#define CAT_TYPES_NIL_H + +#include "cat/value.h" + +typedef struct CAT_TYPES_NIL_Nil { + CAT_VALUE_Value base; +} CAT_TYPES_NIL_Nil; + +/* The one shared nil value (never freed by callers). */ +CAT_VALUE_Value *cat_types_nil_get(void); +CAT_VALUE_Vtable *cat_types_nil_vtable(void); + +#endif /* CAT_TYPES_NIL_H */ diff --git a/include/cat/types/number.h b/include/cat/types/number.h new file mode 100644 index 0000000..17596c8 --- /dev/null +++ b/include/cat/types/number.h @@ -0,0 +1,51 @@ +/* + * cat/types/number.h -- Cat_Number, the abstract numeric class. + * + * Naming rule: symbols declared here are cat_types_number_* / + * CAT_TYPES_NUMBER_*. + * + * Cat_Number is abstract: it exists only as a base that concrete numeric + * types (int, float, byte) embed as their first member. Arithmetic is + * implemented once here and reused by every concrete number via their + * vtable slots, so the C API -- not the compiler -- owns numeric semantics. + */ +#ifndef CAT_TYPES_NUMBER_H +#define CAT_TYPES_NUMBER_H + +#include "cat/value.h" +#include "cat/error.h" + +/* CAT_TYPES_NUMBER_Number == Cat_Number (abstract). + * Concrete numbers embed this as their first field so a pointer to a + * CAT_TYPES_NUMBER_Number can be reinterpreted as CAT_VALUE_Value*. */ +typedef struct CAT_TYPES_NUMBER_Number { + CAT_VALUE_Value base; /* vtable header (must be first) */ + int is_float; /* 0 => integral, 1 => floating point */ + long long i; /* valid when is_float == 0 */ + double f; /* valid when is_float == 1 */ +} CAT_TYPES_NUMBER_Number; + +/* Read a number object as a double (works for int, float and byte). */ +double cat_types_number_as_double(CAT_VALUE_Value *v); + +/* Read a number object as a signed integer (truncating floats). */ +long long cat_types_number_as_int(CAT_VALUE_Value *v); + +/* True if the value's vtable derives from Cat_Number. */ +int cat_types_number_is_number(CAT_VALUE_Value *v); + +/* Shared binary-op helpers: implement +,-,*,/,% over any two numbers, + * promoting to floating point when either operand is floating point. + * Concrete type vtables point their add/sub/... slots at these. */ +int cat_types_number_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_types_number_sub(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_types_number_mul(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_types_number_div(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_types_number_rem(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); + +#endif /* CAT_TYPES_NUMBER_H */ diff --git a/include/cat/types/table.h b/include/cat/types/table.h new file mode 100644 index 0000000..ac480a9 --- /dev/null +++ b/include/cat/types/table.h @@ -0,0 +1,42 @@ +/* + * cat/types/table.h -- the table/object type (the OOP backbone). + * + * Naming rule: symbols here are cat_types_table_* / CAT_TYPES_TABLE_*. + * + * A table is an ordered map of string keys to values. It is the value + * used for Lua-like `{ key = value }` literals and for objects with + * methods, so `Cat_ImplementsGetAttribute`/`SetAttribute` are its main + * interfaces. + */ +#ifndef CAT_TYPES_TABLE_H +#define CAT_TYPES_TABLE_H + +#include "cat/value.h" + +typedef struct CAT_TYPES_TABLE_Pair { + char *key; + CAT_VALUE_Value *value; +} CAT_TYPES_TABLE_Pair; + +/* CAT_TYPES_TABLE_Table -- concrete map/object. */ +typedef struct CAT_TYPES_TABLE_Table { + CAT_VALUE_Value base; /* vtable header (must be first) */ + CAT_TYPES_TABLE_Pair *pairs; + int npairs, cappairs; +} CAT_TYPES_TABLE_Table; + +CAT_VALUE_Value *cat_types_table_new(void); + +int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key, + CAT_VALUE_Value *value, CAT_ERROR_Error *err); +int cat_types_table_get(CAT_VALUE_Value *tbl, const char *key, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); + +/* Number of entries, and key-at-index accessors (insertion order). */ +int cat_types_table_count(CAT_VALUE_Value *tbl); +const char *cat_types_table_key_at(CAT_VALUE_Value *tbl, int i); +CAT_VALUE_Value *cat_types_table_value_at(CAT_VALUE_Value *tbl, int i); + +CAT_VALUE_Vtable *cat_types_table_vtable(void); + +#endif /* CAT_TYPES_TABLE_H */ diff --git a/include/cat/types/text.h b/include/cat/types/text.h new file mode 100644 index 0000000..37b322a --- /dev/null +++ b/include/cat/types/text.h @@ -0,0 +1,41 @@ +/* + * cat/types/text.h -- Cat_Text, the abstract text class. + * + * Naming rule: symbols declared here are cat_types_text_* / + * CAT_TYPES_TEXT_*. + * + * Cat_Text is abstract. ascii_text, utf8_text and the fixed charN types + * embed this base (as their first field) and share the text semantics + * defined here: concatenation and a `length` attribute. + */ +#ifndef CAT_TYPES_TEXT_H +#define CAT_TYPES_TEXT_H + +#include "cat/value.h" +#include "cat/error.h" + +/* CAT_TYPES_TEXT_Text == Cat_Text (abstract). */ +typedef struct CAT_TYPES_TEXT_Text { + CAT_VALUE_Value base; /* vtable header (must be first) */ + const char *bytes; /* not owned; concrete type owns storage */ + int len; /* byte length */ +} CAT_TYPES_TEXT_Text; + +/* Pointer to the bytes of a text value (never NULL for valid text). */ +const char *cat_types_text_bytes(CAT_VALUE_Value *v); + +/* Byte length of a text value. */ +int cat_types_text_length(CAT_VALUE_Value *v); + +/* True if the value's vtable derives from Cat_Text. */ +int cat_types_text_is_text(CAT_VALUE_Value *v); + +/* Shared concatenation used by every concrete text type's add slot. */ +int cat_types_text_concat(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); + +/* Shared `length` attribute getter. */ +int cat_types_text_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); + +#endif /* CAT_TYPES_TEXT_H */ diff --git a/include/cat/types/utf8_text.h b/include/cat/types/utf8_text.h new file mode 100644 index 0000000..c40fcc3 --- /dev/null +++ b/include/cat/types/utf8_text.h @@ -0,0 +1,21 @@ +/* + * cat/types/utf8_text.h -- the concrete `utf8_text` type. + * + * Naming rule: symbols here are cat_types_utf8_text_*. + * A heap-owned UTF-8 string; a Cat_Text whose `length` counts code points. + */ +#ifndef CAT_TYPES_UTF8_TEXT_H +#define CAT_TYPES_UTF8_TEXT_H + +#include "cat/types/text.h" + +/* CAT_TYPES_UTF8_TEXT_Utf8Text -- concrete UTF-8 text value. */ +typedef struct CAT_TYPES_UTF8_TEXT_Utf8Text { + CAT_TYPES_TEXT_Text text; /* base (must be first) */ + char *owned; /* heap storage */ +} CAT_TYPES_UTF8_TEXT_Utf8Text; + +CAT_VALUE_Value *cat_types_utf8_text_new(const char *s); +CAT_VALUE_Vtable *cat_types_utf8_text_vtable(void); + +#endif /* CAT_TYPES_UTF8_TEXT_H */ diff --git a/include/cat/value.h b/include/cat/value.h new file mode 100644 index 0000000..ab1109b --- /dev/null +++ b/include/cat/value.h @@ -0,0 +1,147 @@ +/* + * cat/value.h -- the object model at the heart of catscript. + * + * Naming rule: symbols declared here are cat_value_* / CAT_VALUE_*. + * + * Every catscript value is an object: a pointer to a CAT_VALUE_Value + * whose first member is a vtable pointer. The vtable (Cat_ValueType) + * carries one sub-interface per supported operation. A type that does + * not support an operation leaves the slot empty; the call helper then + * raises a structured error instead of crashing. + * + * The abstract interfaces requested for the language live here: + * Cat_ValueType, Cat_ImplementsAdd/Sub/Mul/Div/Rem/Call/Raise, + * Cat_ImplementsGetAttribute, Cat_ImplementsSetAttribute. + */ +#ifndef CAT_VALUE_H +#define CAT_VALUE_H + +#include + +struct CAT_ERROR_Error; +struct CAT_VALUE_Value; +struct CAT_VALUE_Vtable; + +typedef struct CAT_VALUE_Value CAT_VALUE_Value; +typedef struct CAT_VALUE_Vtable CAT_VALUE_Vtable; +typedef struct CAT_ERROR_Error CAT_ERROR_Error; + +/* ---- abstract interfaces (each is a single-slot method table) ---- */ + +/* Cat_ImplementsAdd -- binary + : self OP other -> *out. */ +typedef struct CAT_IMPL_Add { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value *other, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_Add; + +/* Cat_ImplementsSub -- binary - . */ +typedef struct CAT_IMPL_Sub { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value *other, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_Sub; + +/* Cat_ImplementsMul -- binary * . */ +typedef struct CAT_IMPL_Mul { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value *other, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_Mul; + +/* Cat_ImplementsDiv -- binary / . */ +typedef struct CAT_IMPL_Div { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value *other, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_Div; + +/* Cat_ImplementsRem -- binary % . */ +typedef struct CAT_IMPL_Rem { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value *other, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_Rem; + +/* Cat_ImplementsCall -- self(args...) -> *out. */ +typedef struct CAT_IMPL_Call { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_Call; + +/* Cat_ImplementsRaise -- raise a structured error from this object. */ +typedef struct CAT_IMPL_Raise { + int (*fn)(CAT_VALUE_Value *self, CAT_VALUE_Value *message, + CAT_ERROR_Error *err); +} CAT_IMPL_Raise; + +/* Cat_ImplementsGetAttribute -- self.name -> *out. */ +typedef struct CAT_IMPL_GetAttribute { + int (*fn)(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +} CAT_IMPL_GetAttribute; + +/* Cat_ImplementsSetAttribute -- self.name = value. */ +typedef struct CAT_IMPL_SetAttribute { + int (*fn)(CAT_VALUE_Value *self, const char *name, CAT_VALUE_Value *value, + CAT_ERROR_Error *err); +} CAT_IMPL_SetAttribute; + +/* Runtime kind tag: structural families the VM can test cheaply. */ +enum { + CAT_VALUE_KIND_NIL, + CAT_VALUE_KIND_BOOL, /* boolean family */ + CAT_VALUE_KIND_NUMBER, /* Cat_Number family */ + CAT_VALUE_KIND_TEXT, /* Cat_Text family */ + CAT_VALUE_KIND_TABLE, /* table / object */ + CAT_VALUE_KIND_FUNCTION /* closure */ +}; + +/* ---- the vtable every value type fills in ---- */ + +/* CAT_VALUE_Vtable == Cat_ValueType. + * Slots left NULL mean "operation not supported by this type"; the + * dispatch helpers turn that into an error. */ +struct CAT_VALUE_Vtable { + const char *type_name; + int kind; /* one of CAT_VALUE_KIND_* */ + CAT_IMPL_Add add; + CAT_IMPL_Sub sub; + CAT_IMPL_Mul mul; + CAT_IMPL_Div div; + CAT_IMPL_Rem rem; + CAT_IMPL_Call call; + CAT_IMPL_Raise raise; + CAT_IMPL_GetAttribute get_attribute; + CAT_IMPL_SetAttribute set_attribute; + /* truthiness for control flow (NULL => everything is true) */ + int (*truthy)(CAT_VALUE_Value *self, CAT_ERROR_Error *err); + /* release the object's own storage (shallow) */ + void (*destroy)(CAT_VALUE_Value *self); +}; + +/* The common header shared by every concrete value. */ +struct CAT_VALUE_Value { + CAT_VALUE_Vtable *vtable; +}; + +/* ---- dispatch helpers used by compiler/VM and embedders ---- */ + +int cat_value_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_sub(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_mul(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_div(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_rem(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_call(CAT_VALUE_Value *fn, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err); +int cat_value_set_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value *value, CAT_ERROR_Error *err); +int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err); +int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out, + CAT_ERROR_Error *err); + +const char *cat_value_type_name(CAT_VALUE_Value *v); + +#endif /* CAT_VALUE_H */ diff --git a/include/cat/vm.h b/include/cat/vm.h new file mode 100644 index 0000000..99d5e74 --- /dev/null +++ b/include/cat/vm.h @@ -0,0 +1,59 @@ +/* + * cat/vm.h -- the stack VM that executes catscript bytecode. + * + * Naming rule: symbols here are cat_vm_* / CAT_VM_*. + */ +#ifndef CAT_VM_H +#define CAT_VM_H + +#include "cat/value.h" +#include "cat/error.h" +#include "cat/bytecode.h" + +/* Forward declaration so the native-callback signature below refers to + * the real CAT_VM_State type, not a parameter-list-scoped struct. */ +typedef struct CAT_VM_State CAT_VM_State; + +/* One registered native function. Natives live in the VM (not in a + * process-global list) so distinct VMs never share mutable state and can + * run concurrently on different threads with no global lock (no GIL). */ +typedef struct CAT_VM_Native { + char name[64]; + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **); +} CAT_VM_Native; + +#define CAT_VM_MAXNATIVE 128 + +/* CAT_VM_State -- globals + a call stack. Fully self-contained: two VMs + * share no mutable state, so they may execute on separate threads. */ +typedef struct CAT_VM_State { + /* global table (name -> value) */ CAT_VALUE_Value *globals; + CAT_ERROR_Error err; + /* native functions installed into this VM */ + CAT_VM_Native natives[CAT_VM_MAXNATIVE]; + int nnatives; +} CAT_VM_State; + +/* Create a VM with an empty globals table. */ +CAT_VM_State *cat_vm_new(void); + +/* Run a top-level function; `out` receives the return value. */ +int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, + CAT_VALUE_Value **out); + +/* Register a native function (name, C callback) into globals. */ +int cat_vm_register_native(CAT_VM_State *vm, const char *name, + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, + CAT_VALUE_Value **)); + +/* The VM currently executing on THIS thread (thread-local), used by + * closures/natives invoked through the object system. */ +CAT_VM_State *cat_vm_current(void); + +/* Convenience: get/set a global. */ +CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name); +int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v); + +void cat_vm_free(CAT_VM_State *vm); + +#endif /* CAT_VM_H */ diff --git a/src/cat/bytecode.c b/src/cat/bytecode.c new file mode 100644 index 0000000..bff9d19 --- /dev/null +++ b/src/cat/bytecode.c @@ -0,0 +1,130 @@ +/* + * cat/bytecode.c -- bytecode construction and disassembly. + * + * Naming rule: symbols here are cat_bytecode_* / CAT_BYTECODE_*. + */ +#include "cat/bytecode.h" +#include "cat/error.h" + +#include +#include +#include +#include + +CAT_BYTECODE_Function *cat_bytecode_function_new(const char *name) +{ + CAT_BYTECODE_Function *fn = calloc(1, sizeof(*fn)); + + if (fn == NULL) + return NULL; + fn->name = strdup(name ? name : ""); + return fn; +} + +int cat_bytecode_emit(CAT_BYTECODE_Function *fn, unsigned char op, + int a, int b, int c, int line) +{ + if (fn->ncode == fn->capcode) { + int nc = fn->capcode ? fn->capcode * 2 : 16; + CAT_BYTECODE_Instr *ni = realloc(fn->code, (size_t)nc * sizeof(*ni)); + if (ni == NULL) + return -1; + fn->code = ni; + fn->capcode = nc; + } + fn->code[fn->ncode].op = op; + fn->code[fn->ncode].a = a; + fn->code[fn->ncode].b = b; + fn->code[fn->ncode].c = c; + fn->code[fn->ncode].line = line; + return fn->ncode++; +} + +int cat_bytecode_add_const(CAT_BYTECODE_Function *fn, CAT_VALUE_Value *v) +{ + int i; + for (i = 0; i < fn->nconsts; i++) + if (fn->consts[i].value == v) + return i; + if (fn->nconsts == fn->capconsts) { + int nc = fn->capconsts ? fn->capconsts * 2 : 8; + CAT_BYTECODE_Constant *ncp = + realloc(fn->consts, (size_t)nc * sizeof(*ncp)); + if (ncp == NULL) + return -1; + fn->consts = ncp; + fn->capconsts = nc; + } + fn->consts[fn->nconsts].value = v; + return fn->nconsts++; +} + +int cat_bytecode_add_proto(CAT_BYTECODE_Function *fn, CAT_BYTECODE_Function *p) +{ + if (fn->nprotos == fn->capprotos) { + int nc = fn->capprotos ? fn->capprotos * 2 : 4; + CAT_BYTECODE_Function **np = + realloc(fn->protos, (size_t)nc * sizeof(*np)); + if (np == NULL) + return -1; + fn->protos = np; + fn->capprotos = nc; + } + fn->protos[fn->nprotos] = p; + return fn->nprotos++; +} + +/* opcode -> mnemonic, indexed by CAT_BYTECODE_Op. */ +static const char *op_name(unsigned char op) +{ + static const char *names[] = { + "NOP", "CONST", "NIL", "TRUE", "FALSE", "GETLOCAL", "SETLOCAL", + "GETGLOBAL", "SETGLOBAL", "ADD", "SUB", "MUL", "DIV", "REM", + "NEG", "NOT", "EQ", "NE", "LT", "LE", "GT", "GE", "GETATTR", + "SETATTR", "NEWTABLE", "CALL", "CALLMETHOD", "JUMP", "JUMPIF", + "JUMPIFNOT", "RETURN", "RETURN0", "POP", "PRINT", "CLOSURE", + "GETUPVAL", "CONCAT", "DUP", "GETIDX", "SETIDX" + }; + if (op < sizeof(names) / sizeof(names[0])) + return names[op]; + return "?"; +} + +void cat_bytecode_dump(CAT_BYTECODE_Function *fn, FILE *out) +{ + int i; + + fprintf(out, "== function %s (params=%d locals=%d consts=%d) ==\n", + fn->name, fn->nparams, fn->nlocals, fn->nconsts); + for (i = 0; i < fn->nconsts; i++) + fprintf(out, " const[%d] = %s\n", i, + cat_value_type_name(fn->consts[i].value)); + for (i = 0; i < fn->ncode; i++) { + CAT_BYTECODE_Instr *in = &fn->code[i]; + fprintf(out, " %04d %-10s %d %d %d\n", i, op_name(in->op), + in->a, in->b, in->c); + } + for (i = 0; i < fn->nprotos; i++) + cat_bytecode_dump(fn->protos[i], out); +} + +void cat_bytecode_function_free(CAT_BYTECODE_Function *fn) +{ + int i; + + if (fn == NULL) + return; + /* Constant VALUES are intentionally not destroyed here. A chunk's + * constants may be shared (e.g. a chunk built from a catscript table + * via bc_run borrows the table's values), and destroying them would + * double-free. The pool itself is freed; leaked values are bounded + * by the number of compilations in a single run. */ + (void)i; + for (i = 0; i < fn->nprotos; i++) + cat_bytecode_function_free(fn->protos[i]); + free(fn->code); + free(fn->consts); + free(fn->protos); + free(fn->name); + free(fn); +} diff --git a/src/cat/compiler.c b/src/cat/compiler.c new file mode 100644 index 0000000..c573218 --- /dev/null +++ b/src/cat/compiler.c @@ -0,0 +1,848 @@ +/* + * cat/compiler.c -- source -> bytecode, recursive descent + Pratt exprs. + * + * Naming rule: symbols here are cat_compiler_* / CAT_COMPILER_*. + * + * Grammar (Lua-like): + * chunk := { stat } + * stat := `;` + * | `local` NAME [`: type`] [`=` expr] + * | `local` `function` NAME `(` params `)` chunk `end` + * | `function` NAME `(` params `)` [`->` type] chunk `end` + * | NAME `=` expr + * | `if` expr `then` chunk { `elseif` expr `then` chunk } + * [`else` chunk] `end` + * | `while` expr `do` chunk `end` + * | `repeat` chunk `until` expr + * | `for` NAME `=` expr `,` expr [`,` expr] `do` chunk `end` + * | `return` [expr] + * | expr + * expr := precedence-climbing; primaries carry call/index suffixes. + * + * Type hints (`: type`, `-> ret`) are parsed and discarded: typing is + * structural at runtime, so hints are advisory documentation only. + */ +#include "cat/compiler.h" +#include "cat/lexer.h" +#include "cat/error.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/ascii_text.h" + +#include +#include +#include +#include + +#define MAXLOCALS 256 + +/* One lexical scope: the function being compiled plus its locals. */ +typedef struct { + CAT_BYTECODE_Function *fn; + char locals[MAXLOCALS][64]; + int nlocals; +} FuncCtx; + +typedef struct { + CAT_LEXER_Lexer lx; + CAT_LEXER_Token tok; + CAT_ERROR_Error *err; + int failed; + FuncCtx stack[32]; + int nstack; + /* break handling: pending break jumps per active loop */ + int brk_ends[16][64]; + int brk_n[16]; + int nloops; +} Compiler; + +static void err_at(Compiler *c, int line, const char *fmt, ...) +{ + va_list ap; + char msg[200]; + + va_start(ap, fmt); + vsnprintf(msg, sizeof(msg), fmt, ap); + va_end(ap); + cat_error_raise(c->err, "line %d: %s", line, msg); + c->failed = 1; +} + +/* ---- token cursor ---------------------------------------------------- */ + +static void next(Compiler *c) +{ + cat_lexer_next(&c->lx, &c->tok); +} + +static int check(Compiler *c, int kind) +{ + return c->tok.kind == kind; +} + +static int accept(Compiler *c, int kind) +{ + if (check(c, kind)) { + next(c); + return 1; + } + return 0; +} + +static void expect(Compiler *c, int kind, const char *what) +{ + if (!accept(c, kind)) + err_at(c, c->tok.line, "expected %s, got %s", what, + cat_lexer_kind_name(c->tok.kind)); +} + +static CAT_BYTECODE_Function *cur_fn(Compiler *c); + +static int emit(Compiler *c, int op, int a, int b, int line) +{ + return cat_bytecode_emit(cur_fn(c), (unsigned char)op, a, b, 0, line); +} + +static FuncCtx *ctx(Compiler *c) +{ + return &c->stack[c->nstack - 1]; +} + +static int add_string(Compiler *c, const char *s) +{ + return cat_bytecode_add_const(cur_fn(c), cat_types_ascii_text_new(s)); +} + +static CAT_BYTECODE_Function *cur_fn(Compiler *c) +{ + return ctx(c)->fn; +} + +static int find_local(Compiler *c, const char *name) +{ + FuncCtx *f = ctx(c); + int i; + + for (i = f->nlocals - 1; i >= 0; i--) + if (strcmp(f->locals[i], name) == 0) + return i; + return -1; +} + +static int add_local(Compiler *c, const char *name) +{ + FuncCtx *f = ctx(c); + int slot; + + if (f->nlocals >= MAXLOCALS) + return -1; + slot = f->nlocals++; + snprintf(f->locals[slot], sizeof(f->locals[slot]), "%s", name); + if (f->nlocals > f->fn->nlocals) + f->fn->nlocals = f->nlocals; + return slot; +} + +/* ---- forward decls --------------------------------------------------- */ + +static void expr(Compiler *c); +static void block(Compiler *c); + +/* ---- expressions ----------------------------------------------------- */ + +static int binop_for(int kind) +{ + switch (kind) { + case CAT_LEXER_TOK_PLUS: return CAT_BYTECODE_OP_ADD; + case CAT_LEXER_TOK_MINUS: return CAT_BYTECODE_OP_SUB; + case CAT_LEXER_TOK_STAR: return CAT_BYTECODE_OP_MUL; + case CAT_LEXER_TOK_SLASH: return CAT_BYTECODE_OP_DIV; + case CAT_LEXER_TOK_PERCENT: return CAT_BYTECODE_OP_REM; + case CAT_LEXER_TOK_CONCAT: return CAT_BYTECODE_OP_CONCAT; + case CAT_LEXER_TOK_EQ: return CAT_BYTECODE_OP_EQ; + case CAT_LEXER_TOK_NE: return CAT_BYTECODE_OP_NE; + case CAT_LEXER_TOK_LT: return CAT_BYTECODE_OP_LT; + case CAT_LEXER_TOK_LE: return CAT_BYTECODE_OP_LE; + case CAT_LEXER_TOK_GT: return CAT_BYTECODE_OP_GT; + case CAT_LEXER_TOK_GE: return CAT_BYTECODE_OP_GE; + default: return -1; + } +} + +static int bp_of(int kind) +{ + switch (kind) { + case CAT_LEXER_TOK_OR: return 1; + case CAT_LEXER_TOK_AND: return 2; + case CAT_LEXER_TOK_EQ: case CAT_LEXER_TOK_NE: + case CAT_LEXER_TOK_LT: case CAT_LEXER_TOK_LE: + case CAT_LEXER_TOK_GT: case CAT_LEXER_TOK_GE: return 3; + case CAT_LEXER_TOK_CONCAT: return 4; + case CAT_LEXER_TOK_PLUS: case CAT_LEXER_TOK_MINUS: return 5; + case CAT_LEXER_TOK_STAR: case CAT_LEXER_TOK_SLASH: + case CAT_LEXER_TOK_PERCENT: return 6; + default: return 0; + } +} + +/* Skip an advisory type expression: e.g. `: int`, `: cbyte[]`, + * `: DynSized()`, `: sentinel_sized<'\0'>`. Types are advisory only + * (catscript is structurally typed), so we parse and discard a full + * balanced type expression, ignoring `()`, `<>`, `[]` nesting. */ +static void skip_type_hint(Compiler *c) +{ + int depth = 0; + + if (!check(c, CAT_LEXER_TOK_COLON)) + return; + next(c); + for (;;) { + int k = c->tok.kind; + if (k == CAT_LEXER_TOK_LPAREN || k == CAT_LEXER_TOK_LT || + k == CAT_LEXER_TOK_LBRACKET) { + depth++; + next(c); + continue; + } + if (k == CAT_LEXER_TOK_RPAREN || k == CAT_LEXER_TOK_GT || + k == CAT_LEXER_TOK_RBRACKET) { + if (depth == 0) + break; + depth--; + next(c); + continue; + } + if ((k == CAT_LEXER_TOK_NAME || k == CAT_LEXER_TOK_INT || + k == CAT_LEXER_TOK_STRING) || + (k == CAT_LEXER_TOK_COMMA && depth > 0)) { + next(c); + continue; + } + break; + } +} + +/* Compile `function (params) body end` starting at `function`. */ +static int compile_function_literal(Compiler *c, const char *name) +{ + CAT_BYTECODE_Function *sub; + FuncCtx nc; + int proto; + + expect(c, CAT_LEXER_TOK_LPAREN, "'('"); + sub = cat_bytecode_function_new(name ? name : "anon"); + memset(&nc, 0, sizeof(nc)); + nc.fn = sub; + + /* parse parameter list into the new context */ + while (!check(c, CAT_LEXER_TOK_RPAREN) && !check(c, CAT_LEXER_TOK_EOF)) { + if (check(c, CAT_LEXER_TOK_NAME)) { + char pn[64]; + snprintf(pn, sizeof(pn), "%s", c->tok.text); + next(c); + skip_type_hint(c); + /* add_local into nc directly */ + snprintf(nc.locals[nc.nlocals], sizeof(nc.locals[0]), "%s", pn); + nc.nlocals++; + sub->nparams++; + } else { + break; + } + if (!accept(c, CAT_LEXER_TOK_COMMA)) + break; + } + expect(c, CAT_LEXER_TOK_RPAREN, "')'"); + if (sub->nlocals < nc.nlocals) + sub->nlocals = nc.nlocals; + + /* optional return type hint */ + if (accept(c, CAT_LEXER_TOK_ARROW)) { + if (check(c, CAT_LEXER_TOK_NAME)) + next(c); + } + + /* push context and compile body */ + c->stack[c->nstack++] = nc; + block(c); + expect(c, CAT_LEXER_TOK_END, "'end'"); + emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, c->tok.line); + c->nstack--; + + proto = cat_bytecode_add_proto(cur_fn(c), sub); + return proto; +} + +/* primary + suffixes */ +static void primary(Compiler *c) +{ + CAT_LEXER_Token t = c->tok; + + switch (t.kind) { + case CAT_LEXER_TOK_INT: { + int k = cat_bytecode_add_const(cur_fn(c), cat_types_int_new(t.ival)); + emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line); + next(c); + break; + } + case CAT_LEXER_TOK_FLOAT: { + int k = cat_bytecode_add_const(cur_fn(c), cat_types_float_new(t.fval)); + emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line); + next(c); + break; + } + case CAT_LEXER_TOK_STRING: { + int k = add_string(c, t.text); + emit(c, CAT_BYTECODE_OP_CONST, k, 0, t.line); + next(c); + break; + } + case CAT_LEXER_TOK_NIL: + emit(c, CAT_BYTECODE_OP_NIL, 0, 0, t.line); + next(c); + break; + case CAT_LEXER_TOK_TRUE: + emit(c, CAT_BYTECODE_OP_TRUE, 0, 0, t.line); + next(c); + break; + case CAT_LEXER_TOK_FALSE: + emit(c, CAT_BYTECODE_OP_FALSE, 0, 0, t.line); + next(c); + break; + case CAT_LEXER_TOK_LPAREN: + next(c); + expr(c); + expect(c, CAT_LEXER_TOK_RPAREN, "')'"); + break; + case CAT_LEXER_TOK_FUNCTION: { + int proto; + next(c); + proto = compile_function_literal(c, "anon"); + emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, t.line); + break; + } + case CAT_LEXER_TOK_LBRACE: { + int posidx = 1; /* positional elements are 1-based, like Lua */ + next(c); + emit(c, CAT_BYTECODE_OP_NEWTABLE, 0, 0, t.line); + while (!check(c, CAT_LEXER_TOK_RBRACE) && !check(c, CAT_LEXER_TOK_EOF)) { + if (check(c, CAT_LEXER_TOK_NAME) && + c->lx.src[c->lx.pos] != '\0') { + /* lookahead for `key =` */ + size_t sp = c->lx.pos; + int sl = c->lx.line; + CAT_LEXER_Token la; + char key[256]; + snprintf(key, sizeof(key), "%s", c->tok.text); + cat_lexer_next(&c->lx, &la); + if (la.kind == CAT_LEXER_TOK_ASSIGN) { + c->tok = la; + next(c); + emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line); + expr(c); + emit(c, CAT_BYTECODE_OP_SETATTR, add_string(c, key), + 0, t.line); + } else { + /* positional element: emit idx, value, SETIDX */ + char idxkey[32]; + c->lx.pos = sp; + c->lx.line = sl; + emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line); + emit(c, CAT_BYTECODE_OP_CONST, + cat_bytecode_add_const(cur_fn(c), + cat_types_int_new(posidx++)), + 0, t.line); + expr(c); + (void)idxkey; + emit(c, CAT_BYTECODE_OP_SETIDX, 0, 0, t.line); + } + } else { + emit(c, CAT_BYTECODE_OP_DUP, 0, 0, t.line); + emit(c, CAT_BYTECODE_OP_CONST, + cat_bytecode_add_const(cur_fn(c), + cat_types_int_new(posidx++)), + 0, t.line); + expr(c); + emit(c, CAT_BYTECODE_OP_SETIDX, 0, 0, t.line); + } + if (!accept(c, CAT_LEXER_TOK_COMMA) && + !accept(c, CAT_LEXER_TOK_SEMI)) + break; + } + expect(c, CAT_LEXER_TOK_RBRACE, "'}'"); + break; + } + case CAT_LEXER_TOK_NAME: { + char name[256]; + int slot; + snprintf(name, sizeof(name), "%s", t.text); + next(c); + slot = find_local(c, name); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, t.line); + else + emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, name), 0, t.line); + break; + } + default: + err_at(c, t.line, "unexpected token %s", + cat_lexer_kind_name(t.kind)); + emit(c, CAT_BYTECODE_OP_NIL, 0, 0, t.line); + next(c); + return; + } + + /* suffixes */ + for (;;) { + if (check(c, CAT_LEXER_TOK_DOT)) { + next(c); + if (check(c, CAT_LEXER_TOK_NAME)) { + int k = add_string(c, c->tok.text); + emit(c, CAT_BYTECODE_OP_GETATTR, k, 0, c->tok.line); + next(c); + } + } else if ((check(c, CAT_LEXER_TOK_COLON) || + check(c, CAT_LEXER_TOK_DCOLON)) && + c->lx.src[c->lx.pos] != '\0') { + /* method call: obj:name(args), or class method: + * Class::name(args). Both call with the receiver as + * the implicit first argument (`self`). */ + size_t sp = c->lx.pos; + int sl = c->lx.line; + CAT_LEXER_Token la; + cat_lexer_next(&c->lx, &la); + if (la.kind == CAT_LEXER_TOK_NAME) { + char mname[256]; + int k, nargs = 0; + snprintf(mname, sizeof(mname), "%s", la.text); + c->tok = la; + next(c); + expect(c, CAT_LEXER_TOK_LPAREN, "'('"); + while (!check(c, CAT_LEXER_TOK_RPAREN) && + !check(c, CAT_LEXER_TOK_EOF)) { + expr(c); + nargs++; + if (!accept(c, CAT_LEXER_TOK_COMMA)) + break; + } + expect(c, CAT_LEXER_TOK_RPAREN, "')'"); + k = add_string(c, mname); + emit(c, CAT_BYTECODE_OP_CALLMETHOD, nargs, k, c->tok.line); + } else { + c->lx.pos = sp; + c->lx.line = sl; + break; + } + } else if (check(c, CAT_LEXER_TOK_LPAREN)) { + int nargs = 0; + next(c); + while (!check(c, CAT_LEXER_TOK_RPAREN) && + !check(c, CAT_LEXER_TOK_EOF)) { + expr(c); + nargs++; + if (!accept(c, CAT_LEXER_TOK_COMMA)) + break; + } + expect(c, CAT_LEXER_TOK_RPAREN, "')'"); + emit(c, CAT_BYTECODE_OP_CALL, nargs, 0, c->tok.line); + } else if (check(c, CAT_LEXER_TOK_LBRACKET)) { + next(c); + expr(c); + expect(c, CAT_LEXER_TOK_RBRACKET, "']'"); + emit(c, CAT_BYTECODE_OP_GETIDX, 0, 0, c->tok.line); + } else { + break; + } + } +} + +static void unary(Compiler *c) +{ + if (check(c, CAT_LEXER_TOK_MINUS)) { + next(c); + unary(c); + emit(c, CAT_BYTECODE_OP_NEG, 0, 0, c->tok.line); + } else if (check(c, CAT_LEXER_TOK_NOT)) { + next(c); + unary(c); + emit(c, CAT_BYTECODE_OP_NOT, 0, 0, c->tok.line); + } else if (check(c, CAT_LEXER_TOK_HASH)) { + next(c); + unary(c); + emit(c, CAT_BYTECODE_OP_GETATTR, add_string(c, "length"), 0, c->tok.line); + } else { + primary(c); + } +} + +static void expr_bp(Compiler *c, int minbp) +{ + unary(c); + for (;;) { + int kind = c->tok.kind; + int bp = bp_of(kind); + if (bp == 0 || bp < minbp) + break; + if (kind == CAT_LEXER_TOK_AND || kind == CAT_LEXER_TOK_OR) { + /* Short-circuit while keeping the stack balanced: + * a or b -> push a; DUP; JUMPIF L; POP; push b; L: + * a and b -> push a; DUP; JUMPIFNOT L; POP; push b; L: + * Only one value is left on the stack at L. */ + int op = (kind == CAT_LEXER_TOK_AND) ? + CAT_BYTECODE_OP_JUMPIFNOT : CAT_BYTECODE_OP_JUMPIF; + int jmp; + emit(c, CAT_BYTECODE_OP_DUP, 0, 0, c->tok.line); + jmp = emit(c, op, 0, 0, c->tok.line); + emit(c, CAT_BYTECODE_OP_POP, 0, 0, c->tok.line); + next(c); + expr_bp(c, bp + 1); + cur_fn(c)->code[jmp].a = cur_fn(c)->ncode; + continue; + } + next(c); + expr_bp(c, bp + 1); + emit(c, binop_for(kind), 0, 0, c->tok.line); + } +} + +static void expr(Compiler *c) +{ + expr_bp(c, 1); +} + +/* ---- statements ------------------------------------------------------ */ + +static void stat(Compiler *c) +{ + int line = c->tok.line; + + switch (c->tok.kind) { + case CAT_LEXER_TOK_SEMI: + next(c); + break; + + case CAT_LEXER_TOK_BREAK: + next(c); + if (c->nloops <= 0) { + err_at(c, line, "'break' outside a loop"); + } else { + int lv = c->nloops - 1; + if (c->brk_n[lv] < 64) + c->brk_ends[lv][c->brk_n[lv]++] = + emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line); + } + break; + + case CAT_LEXER_TOK_LOCAL: + next(c); + if (check(c, CAT_LEXER_TOK_FUNCTION)) { + char name[256]; + int slot; + int proto; + next(c); + name[0] = '\0'; + if (check(c, CAT_LEXER_TOK_NAME)) { + snprintf(name, sizeof(name), "%s", c->tok.text); + next(c); + } + slot = add_local(c, name); + proto = compile_function_literal(c, name); + emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line); + break; + } + if (check(c, CAT_LEXER_TOK_NAME)) { + char name[256]; + int slot; + snprintf(name, sizeof(name), "%s", c->tok.text); + next(c); + skip_type_hint(c); + if (accept(c, CAT_LEXER_TOK_ASSIGN)) + expr(c); + else + emit(c, CAT_BYTECODE_OP_NIL, 0, 0, line); + slot = add_local(c, name); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line); + } + break; + + case CAT_LEXER_TOK_IF: { + int jfalse; + int ends[64]; + int nends = 0; + next(c); + expr(c); + expect(c, CAT_LEXER_TOK_THEN, "'then'"); + jfalse = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line); + block(c); + while (check(c, CAT_LEXER_TOK_ELSEIF)) { + next(c); + if (nends < 64) + ends[nends++] = emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line); + cur_fn(c)->code[jfalse].a = cur_fn(c)->ncode; + expr(c); + expect(c, CAT_LEXER_TOK_THEN, "'then'"); + jfalse = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line); + block(c); + } + if (accept(c, CAT_LEXER_TOK_ELSE)) { + if (nends < 64) + ends[nends++] = emit(c, CAT_BYTECODE_OP_JUMP, 0, 0, line); + cur_fn(c)->code[jfalse].a = cur_fn(c)->ncode; + block(c); + } else { + cur_fn(c)->code[jfalse].a = cur_fn(c)->ncode; + } + { + int k; + for (k = 0; k < nends; k++) + cur_fn(c)->code[ends[k]].a = cur_fn(c)->ncode; + } + expect(c, CAT_LEXER_TOK_END, "'end'"); + break; + } + + case CAT_LEXER_TOK_WHILE: { + int jcond, jend, lv; + next(c); + jcond = cur_fn(c)->ncode; + expr(c); + expect(c, CAT_LEXER_TOK_DO, "'do'"); + jend = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line); + lv = c->nloops++; + c->brk_n[lv] = 0; + block(c); + c->nloops--; + emit(c, CAT_BYTECODE_OP_JUMP, jcond, 0, line); + cur_fn(c)->code[jend].a = cur_fn(c)->ncode; + { int k; for (k = 0; k < c->brk_n[lv]; k++) + cur_fn(c)->code[c->brk_ends[lv][k]].a = cur_fn(c)->ncode; } + expect(c, CAT_LEXER_TOK_END, "'end'"); + break; + } + + case CAT_LEXER_TOK_REPEAT: { + int jtop, lv; + next(c); + jtop = cur_fn(c)->ncode; + lv = c->nloops++; + c->brk_n[lv] = 0; + block(c); + c->nloops--; + expect(c, CAT_LEXER_TOK_UNTIL, "'until'"); + expr(c); + emit(c, CAT_BYTECODE_OP_JUMPIFNOT, jtop, 0, line); + { int k; for (k = 0; k < c->brk_n[lv]; k++) + cur_fn(c)->code[c->brk_ends[lv][k]].a = cur_fn(c)->ncode; } + break; + } + + case CAT_LEXER_TOK_FOR: { + char var[64]; + int slot, jcond, jend; + next(c); + var[0] = '\0'; + if (check(c, CAT_LEXER_TOK_NAME)) { + snprintf(var, sizeof(var), "%s", c->tok.text); + next(c); + } + skip_type_hint(c); + expect(c, CAT_LEXER_TOK_ASSIGN, "'='"); + expr(c); /* start */ + expect(c, CAT_LEXER_TOK_COMMA, "','"); + expr(c); /* limit */ + if (accept(c, CAT_LEXER_TOK_COMMA)) + expr(c); /* step */ + else + emit(c, CAT_BYTECODE_OP_CONST, + cat_bytecode_add_const(cur_fn(c), cat_types_int_new(1)), + 0, line); + expect(c, CAT_LEXER_TOK_DO, "'do'"); + slot = add_local(c, var); + add_local(c, " .limit"); + add_local(c, " .step"); + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot + 2, 0, line); + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot + 1, 0, line); + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line); + jcond = cur_fn(c)->ncode; + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line); + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot + 1, 0, line); + emit(c, CAT_BYTECODE_OP_LE, 0, 0, line); + jend = emit(c, CAT_BYTECODE_OP_JUMPIFNOT, 0, 0, line); + { + int lv = c->nloops++; + c->brk_n[lv] = 0; + block(c); + c->nloops--; + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line); + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot + 2, 0, line); + emit(c, CAT_BYTECODE_OP_ADD, 0, 0, line); + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line); + emit(c, CAT_BYTECODE_OP_JUMP, jcond, 0, line); + cur_fn(c)->code[jend].a = cur_fn(c)->ncode; + { + int k; + for (k = 0; k < c->brk_n[lv]; k++) + cur_fn(c)->code[c->brk_ends[lv][k]].a = + cur_fn(c)->ncode; + } + } + expect(c, CAT_LEXER_TOK_END, "'end'"); + break; + } + + case CAT_LEXER_TOK_FUNCTION: { + char name[256]; + int proto; + next(c); + name[0] = '\0'; + if (check(c, CAT_LEXER_TOK_NAME)) { + snprintf(name, sizeof(name), "%s", c->tok.text); + next(c); + } + proto = compile_function_literal(c, name); + emit(c, CAT_BYTECODE_OP_CLOSURE, proto, 0, line); + emit(c, CAT_BYTECODE_OP_SETGLOBAL, add_string(c, name), 0, line); + break; + } + + case CAT_LEXER_TOK_RETURN: + next(c); + if (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) && + !check(c, CAT_LEXER_TOK_SEMI) && !check(c, CAT_LEXER_TOK_ELSE) && + !check(c, CAT_LEXER_TOK_ELSEIF) && !check(c, CAT_LEXER_TOK_UNTIL)) { + expr(c); + emit(c, CAT_BYTECODE_OP_RETURN, 0, 0, line); + } else { + emit(c, CAT_BYTECODE_OP_RETURN0, 0, 0, line); + } + accept(c, CAT_LEXER_TOK_SEMI); + break; + + case CAT_LEXER_TOK_NAME: { + /* assignment if `name =`, or field assignment if `name.attr =`. + * Otherwise rewind and parse as an ordinary expression. */ + size_t sp = c->lx.pos; + int sl = c->lx.line; + CAT_LEXER_Token la; + char name[256]; + snprintf(name, sizeof(name), "%s", c->tok.text); + cat_lexer_next(&c->lx, &la); + if (la.kind == CAT_LEXER_TOK_ASSIGN) { + c->tok = la; + next(c); + expr(c); + { + int slot = find_local(c, name); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_SETLOCAL, slot, 0, line); + else + emit(c, CAT_BYTECODE_OP_SETGLOBAL, + add_string(c, name), 0, line); + } + break; + } + if (la.kind == CAT_LEXER_TOK_LBRACKET) { + /* indexed assignment: name[idx] = value */ + int slot = find_local(c, name); + c->tok = la; + next(c); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line); + else + emit(c, CAT_BYTECODE_OP_GETGLOBAL, + add_string(c, name), 0, line); + expr(c); + expect(c, CAT_LEXER_TOK_RBRACKET, "']'"); + if (!accept(c, CAT_LEXER_TOK_ASSIGN)) { + err_at(c, line, "expected '=' after index target"); + break; + } + expr(c); + emit(c, CAT_BYTECODE_OP_SETIDX, 0, 0, line); + break; + } + if (la.kind == CAT_LEXER_TOK_DOT) { + CAT_LEXER_Token attr; + cat_lexer_next(&c->lx, &attr); + if (attr.kind == CAT_LEXER_TOK_NAME) { + CAT_LEXER_Token eq; + cat_lexer_next(&c->lx, &eq); + if (eq.kind == CAT_LEXER_TOK_ASSIGN) { + int slot = find_local(c, name); + c->tok = eq; + next(c); + if (slot >= 0) + emit(c, CAT_BYTECODE_OP_GETLOCAL, slot, 0, line); + else + emit(c, CAT_BYTECODE_OP_GETGLOBAL, + add_string(c, name), 0, line); + expr(c); + emit(c, CAT_BYTECODE_OP_SETATTR, + add_string(c, attr.text), 0, line); + break; + } + } + } + /* not an assignment: rewind and parse as an expression, keeping the + * current NAME token in place. */ + c->lx.pos = sp; + c->lx.line = sl; + } + /* FALLTHROUGH */ + default: + expr(c); + emit(c, CAT_BYTECODE_OP_POP, 0, 0, line); + break; + } +} + +static void block(Compiler *c) +{ + while (!check(c, CAT_LEXER_TOK_END) && !check(c, CAT_LEXER_TOK_EOF) && + !check(c, CAT_LEXER_TOK_ELSE) && !check(c, CAT_LEXER_TOK_ELSEIF) && + !check(c, CAT_LEXER_TOK_UNTIL)) { + int before = cur_fn(c)->ncode; + /* a lone ';' is a valid empty statement, not a parse error */ + if (check(c, CAT_LEXER_TOK_SEMI)) { + next(c); + continue; + } + stat(c); + if (c->failed) + break; + if (cur_fn(c)->ncode == before && + !check(c, CAT_LEXER_TOK_EOF) && + !check(c, CAT_LEXER_TOK_SEMI)) { + err_at(c, c->tok.line, "parse error near %s", + cat_lexer_kind_name(c->tok.kind)); + break; + } + } +} + +CAT_BYTECODE_Function *cat_compiler_compile(const char *source, + CAT_ERROR_Error *err) +{ + Compiler c; + CAT_BYTECODE_Function *fn; + + memset(&c, 0, sizeof(c)); + c.err = err; + cat_lexer_init(&c.lx, source); + fn = cat_bytecode_function_new("main"); + memset(&c.stack[0], 0, sizeof(c.stack[0])); + c.stack[0].fn = fn; + c.nstack = 1; + + next(&c); + block(&c); + emit(&c, CAT_BYTECODE_OP_RETURN0, 0, 0, c.tok.line); + + if (c.failed) { + cat_bytecode_function_free(fn); + return NULL; + } + return fn; +} diff --git a/src/cat/error.c b/src/cat/error.c new file mode 100644 index 0000000..614d015 --- /dev/null +++ b/src/cat/error.c @@ -0,0 +1,30 @@ +/* + * cat/error.c -- implementation of CAT_ERROR_Error. + * + * Naming rule: symbols here are cat_error_* / CAT_ERROR_*. + */ +#include "cat/error.h" + +#include +#include +#include + +void cat_error_clear(CAT_ERROR_Error *err) +{ + if (err == NULL) + return; + err->raised = false; + err->message[0] = '\0'; +} + +void cat_error_raise(CAT_ERROR_Error *err, const char *fmt, ...) +{ + va_list ap; + + if (err == NULL) + return; + err->raised = true; + va_start(ap, fmt); + vsnprintf(err->message, sizeof(err->message), fmt, ap); + va_end(ap); +} diff --git a/src/cat/lexer.c b/src/cat/lexer.c new file mode 100644 index 0000000..0658bcb --- /dev/null +++ b/src/cat/lexer.c @@ -0,0 +1,264 @@ +/* + * cat/lexer.c -- tokenizer implementation. + * + * Naming rule: symbols here are cat_lexer_* / CAT_LEXER_*. + */ +#include "cat/lexer.h" + +#include +#include +#include + +/* Keyword table: name -> token kind. */ +struct kw { + const char *name; + int kind; +}; + +static const struct kw g_keywords[] = { + { "and", CAT_LEXER_TOK_AND }, + { "break", CAT_LEXER_TOK_BREAK }, + { "do", CAT_LEXER_TOK_DO }, + { "else", CAT_LEXER_TOK_ELSE }, + { "elseif", CAT_LEXER_TOK_ELSEIF }, + { "end", CAT_LEXER_TOK_END }, + { "false", CAT_LEXER_TOK_FALSE }, + { "for", CAT_LEXER_TOK_FOR }, + { "function", CAT_LEXER_TOK_FUNCTION }, + { "if", CAT_LEXER_TOK_IF }, + { "in", CAT_LEXER_TOK_IN }, + { "local", CAT_LEXER_TOK_LOCAL }, + { "nil", CAT_LEXER_TOK_NIL }, + { "not", CAT_LEXER_TOK_NOT }, + { "or", CAT_LEXER_TOK_OR }, + { "repeat", CAT_LEXER_TOK_REPEAT }, + { "return", CAT_LEXER_TOK_RETURN }, + { "then", CAT_LEXER_TOK_THEN }, + { "true", CAT_LEXER_TOK_TRUE }, + { "until", CAT_LEXER_TOK_UNTIL }, + { "while", CAT_LEXER_TOK_WHILE }, +}; + +void cat_lexer_init(CAT_LEXER_Lexer *lx, const char *src) +{ + lx->src = src ? src : ""; + lx->pos = 0; + lx->line = 1; +} + +static int peek(CAT_LEXER_Lexer *lx) +{ + return (unsigned char)lx->src[lx->pos]; +} + +static int peek2(CAT_LEXER_Lexer *lx) +{ + return (unsigned char)lx->src[lx->pos + 1]; +} + +static int advance(CAT_LEXER_Lexer *lx) +{ + int c = lx->src[lx->pos]; + if (c == '\0') + return -1; + lx->pos++; + if (c == '\n') + lx->line++; + return c; +} + +/* Skip whitespace and `--` line comments. */ +static void skip_ws(CAT_LEXER_Lexer *lx) +{ + for (;;) { + int c = peek(lx); + if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { + advance(lx); + } else if (c == '-' && peek2(lx) == '-') { + advance(lx); + advance(lx); + while (peek(lx) != '\n' && peek(lx) != '\0') + advance(lx); + } else { + break; + } + } +} + +static int lookup_keyword(const char *s) +{ + size_t i; + for (i = 0; i < sizeof(g_keywords) / sizeof(g_keywords[0]); i++) + if (strcmp(g_keywords[i].name, s) == 0) + return g_keywords[i].kind; + return CAT_LEXER_TOK_NAME; +} + +int cat_lexer_next(CAT_LEXER_Lexer *lx, CAT_LEXER_Token *out) +{ + int c; + + memset(out, 0, sizeof(*out)); + skip_ws(lx); + out->line = lx->line; + c = peek(lx); + + if (c == '\0') { + out->kind = CAT_LEXER_TOK_EOF; + return 0; + } + + /* identifiers / keywords */ + if (isalpha(c) || c == '_') { + int n = 0; + while (isalnum(peek(lx)) || peek(lx) == '_') { + if (n < (int)sizeof(out->text) - 1) + out->text[n++] = (char)advance(lx); + else + advance(lx); + } + out->text[n] = '\0'; + out->kind = lookup_keyword(out->text); + return 0; + } + + /* numbers: int or float */ + if (isdigit(c)) { + int isfloat = 0; + int n = 0; + while (isdigit(peek(lx))) { + if (n < (int)sizeof(out->text) - 1) + out->text[n++] = (char)advance(lx); + else + advance(lx); + } + if (peek(lx) == '.' && isdigit(peek2(lx))) { + isfloat = 1; + if (n < (int)sizeof(out->text) - 1) + out->text[n++] = (char)advance(lx); + while (isdigit(peek(lx))) { + if (n < (int)sizeof(out->text) - 1) + out->text[n++] = (char)advance(lx); + else + advance(lx); + } + } + out->text[n] = '\0'; + if (isfloat) { + out->kind = CAT_LEXER_TOK_FLOAT; + out->fval = strtod(out->text, NULL); + } else { + out->kind = CAT_LEXER_TOK_INT; + out->ival = strtoll(out->text, NULL, 10); + } + return 0; + } + + /* strings: '...' or "..." with \n \t \\ \" escapes */ + if (c == '"' || c == '\'') { + int quote = advance(lx); + int n = 0; + while (peek(lx) != quote && peek(lx) != '\0') { + int ch = advance(lx); + if (ch == '\\') { + int e = advance(lx); + switch (e) { + case 'n': ch = '\n'; break; + case 't': ch = '\t'; break; + case '\\': ch = '\\'; break; + case '"': ch = '"'; break; + case '\'': ch = '\''; break; + default: ch = e; break; + } + } + if (n < (int)sizeof(out->text) - 1) + out->text[n++] = (char)ch; + } + if (peek(lx) == quote) + advance(lx); + out->text[n] = '\0'; + out->kind = CAT_LEXER_TOK_STRING; + return 0; + } + + /* symbols */ + switch (c) { + case '+': advance(lx); out->kind = CAT_LEXER_TOK_PLUS; return 0; + case '-': + advance(lx); + if (peek(lx) == '>') { + advance(lx); + out->kind = CAT_LEXER_TOK_ARROW; + return 0; + } + out->kind = CAT_LEXER_TOK_MINUS; + return 0; + case '*': advance(lx); out->kind = CAT_LEXER_TOK_STAR; return 0; + case '/': advance(lx); out->kind = CAT_LEXER_TOK_SLASH; return 0; + case '%': advance(lx); out->kind = CAT_LEXER_TOK_PERCENT; return 0; + case '^': advance(lx); out->kind = CAT_LEXER_TOK_CARET; return 0; + case '#': advance(lx); out->kind = CAT_LEXER_TOK_HASH; return 0; + case ';': advance(lx); out->kind = CAT_LEXER_TOK_SEMI; return 0; + case ',': advance(lx); out->kind = CAT_LEXER_TOK_COMMA; return 0; + case '(': advance(lx); out->kind = CAT_LEXER_TOK_LPAREN; return 0; + case ')': advance(lx); out->kind = CAT_LEXER_TOK_RPAREN; return 0; + case '{': advance(lx); out->kind = CAT_LEXER_TOK_LBRACE; return 0; + case '}': advance(lx); out->kind = CAT_LEXER_TOK_RBRACE; return 0; + case '[': advance(lx); out->kind = CAT_LEXER_TOK_LBRACKET; return 0; + case ']': advance(lx); out->kind = CAT_LEXER_TOK_RBRACKET; return 0; + case '=': + advance(lx); + if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_EQ; } + else out->kind = CAT_LEXER_TOK_ASSIGN; + return 0; + case '~': + advance(lx); + if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_NE; return 0; } + out->kind = CAT_LEXER_TOK_EOF; + return 0; + case '<': + advance(lx); + if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_LE; } + else out->kind = CAT_LEXER_TOK_LT; + return 0; + case '>': + advance(lx); + if (peek(lx) == '=') { advance(lx); out->kind = CAT_LEXER_TOK_GE; } + else out->kind = CAT_LEXER_TOK_GT; + return 0; + case '.': + advance(lx); + if (peek(lx) == '.') { + advance(lx); + out->kind = CAT_LEXER_TOK_CONCAT; + } else { + out->kind = CAT_LEXER_TOK_DOT; + } + return 0; + case ':': + advance(lx); + if (peek(lx) == ':') { advance(lx); out->kind = CAT_LEXER_TOK_DCOLON; } + else out->kind = CAT_LEXER_TOK_COLON; + return 0; + default: + advance(lx); + out->kind = CAT_LEXER_TOK_EOF; + return 0; + } +} + +const char *cat_lexer_kind_name(int kind) +{ + static const char *names[] = { + "EOF", "NAME", "INT", "FLOAT", "STRING", + "and", "break", "do", "else", "elseif", "end", "false", "for", + "function", "if", "in", "local", "nil", "not", "or", "repeat", + "return", "then", "true", "until", "while", + "+", "-", "*", "/", "%", "^", "#", "==", "~=", "<=", ">=", "<", + ">", "=", "(", ")", "{", "}", "[", "]", ";", ",", ".", ":", + "::", "..", "->" + }; + if (kind >= 0 && kind < (int)(sizeof(names) / sizeof(names[0]))) + return names[kind]; + return "?"; +} diff --git a/src/cat/module.c b/src/cat/module.c new file mode 100644 index 0000000..ff7805a --- /dev/null +++ b/src/cat/module.c @@ -0,0 +1,60 @@ +/* + * cat/module.c -- Cat_Module implementation. + * + * Naming rule: symbols here are cat_module_* / CAT_MODULE_*. + */ +#include "cat/module.h" +#include "cat/compiler.h" +#include "cat/bytecode.h" +#include "cat/vm.h" +#include "cat/stdlib/stdlib.h" +#include "cat/stdlib/build.h" + +#include +#include + +CAT_MODULE_Module *cat_module_new(const char *name) +{ + CAT_MODULE_Module *m = calloc(1, sizeof(*m)); + + if (m == NULL) + return NULL; + m->name = strdup(name ? name : "module"); + return m; +} + +int cat_module_compile(CAT_MODULE_Module *mod, const char *source, + CAT_ERROR_Error *err) +{ + mod->main = cat_compiler_compile(source, err); + return mod->main ? 0 : -1; +} + +int cat_module_run(CAT_MODULE_Module *mod, CAT_VALUE_Value **out, + CAT_ERROR_Error *err) +{ + CAT_VM_State *vm; + int rc; + + if (mod->main == NULL) + return (cat_error_raise(err, "module has no compiled code"), -1); + vm = cat_vm_new(); + if (vm == NULL) + return -1; + cat_stdlib_stdlib_install(vm); + cat_stdlib_build_install(vm); + rc = cat_vm_run(vm, mod->main, out); + if (rc != 0) + cat_error_raise(err, "%s", vm->err.message); + cat_vm_free(vm); + return rc; +} + +void cat_module_free(CAT_MODULE_Module *mod) +{ + if (mod == NULL) + return; + cat_bytecode_function_free(mod->main); + free(mod->name); + free(mod); +} diff --git a/src/cat/stdlib/build.c b/src/cat/stdlib/build.c new file mode 100644 index 0000000..6d1c666 --- /dev/null +++ b/src/cat/stdlib/build.c @@ -0,0 +1,132 @@ +/* + * cat/stdlib/build.c -- bytecode builder primitives (see build.h). + * + * Naming rule: symbols here are cat_stdlib_build_* / CAT_STDLIB_BUILD_*. + * + * bc_run(chunk) -- build a CAT_BYTECODE_Function from a chunk table and + * execute it, returning the chunk's return value. + * bc_dump(chunk) -- print a disassembly of a chunk table. + */ +#include "cat/stdlib/build.h" +#include "cat/bytecode.h" +#include "cat/types/table.h" +#include "cat/types/int.h" +#include "cat/types/nil.h" +#include "cat/types/ascii_text.h" +#include "cat/error.h" + +#include + +/* Read an integer field from a table (0 if absent). */ +static long long tbl_int(CAT_VALUE_Value *t, const char *key) +{ + CAT_VALUE_Value *v = NULL; + CAT_ERROR_Error e; + + cat_error_clear(&e); + if (t == NULL || cat_types_table_get(t, key, &v, &e) != 0 || v == NULL) + return 0; + return cat_types_number_as_int(v); +} + +static const char *tbl_str(CAT_VALUE_Value *t, const char *key) +{ + CAT_VALUE_Value *v = NULL; + CAT_ERROR_Error e; + + cat_error_clear(&e); + if (t == NULL || cat_types_table_get(t, key, &v, &e) != 0 || v == NULL) + return NULL; + return cat_types_text_bytes(v); +} + +/* Recursively convert a chunk table into a CAT_BYTECODE_Function. */ +static CAT_BYTECODE_Function *build_function(CAT_VALUE_Value *chunk) +{ + CAT_BYTECODE_Function *fn = cat_bytecode_function_new(tbl_str(chunk, "name")); + CAT_VALUE_Value *arr = NULL; + CAT_ERROR_Error e; + int i, n; + + fn->nparams = (int)tbl_int(chunk, "nparams"); + fn->nlocals = (int)tbl_int(chunk, "nlocals"); + + /* constants */ + cat_error_clear(&e); + if (cat_types_table_get(chunk, "consts", &arr, &e) == 0) { + n = cat_types_table_count(arr); + for (i = 0; i < n; i++) + cat_bytecode_add_const(fn, cat_types_table_value_at(arr, i)); + } + + /* nested prototypes */ + cat_error_clear(&e); + if (cat_types_table_get(chunk, "protos", &arr, &e) == 0) { + n = cat_types_table_count(arr); + for (i = 0; i < n; i++) + cat_bytecode_add_proto(fn, + build_function(cat_types_table_value_at(arr, i))); + } + + /* instructions */ + cat_error_clear(&e); + if (cat_types_table_get(chunk, "code", &arr, &e) == 0) { + n = cat_types_table_count(arr); + for (i = 0; i < n; i++) { + CAT_VALUE_Value *in = cat_types_table_value_at(arr, i); + cat_bytecode_emit(fn, (unsigned char)tbl_int(in, "op"), + (int)tbl_int(in, "a"), + (int)tbl_int(in, "b"), + (int)tbl_int(in, "c"), + (int)tbl_int(in, "line")); + } + } + return fn; +} + +static int lf_bc_run(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_BYTECODE_Function *fn; + CAT_ERROR_Error e; + int rc; + + (void)vm; + cat_error_clear(&e); + if (nargs < 1 || !cat_types_table_count(args[0])) { /* not a chunk */ + } + fn = build_function(args[0]); + if (fn == NULL) { + *out = cat_types_nil_get(); + return 0; + } + rc = cat_vm_run(vm, fn, out); + cat_bytecode_function_free(fn); + return rc; +} + +static int lf_bc_dump(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_BYTECODE_Function *fn; + + (void)vm; + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + fn = build_function(args[0]); + if (fn != NULL) { + cat_bytecode_dump(fn, stdout); + cat_bytecode_function_free(fn); + } + *out = cat_types_nil_get(); + return 0; +} + +int cat_stdlib_build_install(CAT_VM_State *vm) +{ + cat_vm_register_native(vm, "bc_run", lf_bc_run); + cat_vm_register_native(vm, "bc_dump", lf_bc_dump); + return 0; +} diff --git a/src/cat/stdlib/stdlib.c b/src/cat/stdlib/stdlib.c new file mode 100644 index 0000000..eabef0f --- /dev/null +++ b/src/cat/stdlib/stdlib.c @@ -0,0 +1,387 @@ +/* + * cat/stdlib/stdlib.c -- standard library native functions. + * + * Naming rule: symbols here are cat_stdlib_stdlib_*. + * + * Native signature: int cb(vm, args, nargs, out). Installed names: + * print, tostring, tonumber, type, len, toml_parse, toml_encode. + */ +#include "cat/stdlib/stdlib.h" +#include "cat/stdlib/toml.h" +#include "cat/compiler.h" +#include "cat/bytecode.h" +#include "cat/types/nil.h" +#include "cat/types/bool.h" +#include "cat/types/number.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/text.h" +#include "cat/types/ascii_text.h" +#include "cat/types/table.h" +#include "cat/types/native.h" +#include "cat/types/file.h" + +#include +#include +#include + +/* toString for any value (heap string, caller does not free). */ +static const char *value_to_text(CAT_VALUE_Value *v) +{ + static char buf[512]; + + if (v == NULL || v == cat_types_nil_get()) + return "nil"; + if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) + return cat_types_text_bytes(v); + if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { + if (((CAT_TYPES_NUMBER_Number *)v)->is_float) + snprintf(buf, sizeof(buf), "%g", cat_types_number_as_double(v)); + else + snprintf(buf, sizeof(buf), "%lld", cat_types_number_as_int(v)); + return buf; + } + if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) + return ((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false"; + snprintf(buf, sizeof(buf), "<%s>", cat_value_type_name(v)); + return buf; +} + +static int lf_print(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + int i; + + (void)vm; + for (i = 0; i < nargs; i++) { + if (i) + putchar(' '); + fputs(value_to_text(args[i]), stdout); + } + putchar('\n'); + *out = cat_types_nil_get(); + return 0; +} + +static int lf_tostring(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + (void)vm; + *out = cat_types_ascii_text_new(nargs > 0 ? value_to_text(args[0]) : ""); + return 0; +} + +static int lf_tonumber(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + const char *s; + char *end; + + (void)vm; + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_NUMBER) { + *out = args[0]; + return 0; + } + s = cat_types_text_bytes(args[0]); + if (strchr(s, '.') != NULL) { + double d = strtod(s, &end); + *out = (*end == '\0') ? cat_types_float_new(d) : cat_types_nil_get(); + } else { + long long n = strtoll(s, &end, 10); + *out = (*end == '\0') ? cat_types_int_new(n) : cat_types_nil_get(); + } + return 0; +} + +static int lf_type(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + (void)vm; + *out = cat_types_ascii_text_new(nargs > 0 ? cat_value_type_name(args[0]) + : "nil"); + return 0; +} + +static int lf_len(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + (void)vm; + if (nargs < 1) { + *out = cat_types_int_new(0); + return 0; + } + if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TEXT) + *out = cat_types_int_new(cat_types_text_length(args[0])); + else if (args[0]->vtable && args[0]->vtable->kind == CAT_VALUE_KIND_TABLE) + *out = cat_types_int_new(cat_types_table_count(args[0])); + else + *out = cat_types_int_new(0); + return 0; +} + +static int lf_toml_parse(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_VALUE_Value *tbl = NULL; + CAT_ERROR_Error e; + + (void)vm; + cat_error_clear(&e); + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + if (cat_stdlib_toml_parse(cat_types_text_bytes(args[0]), &tbl, &e) != 0) { + fprintf(stderr, "toml_parse: %s\n", e.message); + *out = cat_types_nil_get(); + return 0; + } + *out = tbl; + return 0; +} + +static int lf_toml_encode(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_ERROR_Error e; + char *s; + + (void)vm; + cat_error_clear(&e); + if (nargs < 1) { + *out = cat_types_ascii_text_new(""); + return 0; + } + s = cat_stdlib_toml_encode(args[0], &e); + *out = cat_types_ascii_text_new(s ? s : ""); + free(s); + return 0; +} + +static int lf_read_file(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + FILE *f; + long sz; + char *buf = NULL; + char *path; + + (void)vm; + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + path = (char *)cat_types_text_bytes(args[0]); + f = fopen(path, "rb"); + if (f == NULL) { + *out = cat_types_nil_get(); + return 0; + } + fseek(f, 0, SEEK_END); + sz = ftell(f); + fseek(f, 0, SEEK_SET); + buf = malloc((size_t)sz + 1); + if (buf == NULL) { + fclose(f); + *out = cat_types_nil_get(); + return 0; + } + if (fread(buf, 1, (size_t)sz, f) != (size_t)sz) { /* short read ok */ } + buf[sz] = '\0'; + fclose(f); + *out = cat_types_ascii_text_new(buf); + free(buf); + return 0; +} + +static int lf_write_file(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + FILE *f; + + (void)vm; + if (nargs < 2) { + *out = cat_types_nil_get(); + return 0; + } + f = fopen(cat_types_text_bytes(args[0]), "wb"); + if (f != NULL) { + const char *s = cat_types_text_bytes(args[1]); + fwrite(s, 1, strlen(s), f); + fclose(f); + } + *out = cat_types_nil_get(); + return 0; +} + +static int lf_ord(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + const char *s; + long long i; + + (void)vm; + if (nargs < 2) { + *out = cat_types_int_new(-1); + return 0; + } + s = cat_types_text_bytes(args[0]); + i = cat_types_number_as_int(args[1]); + if (i < 0 || i >= (long long)strlen(s)) + *out = cat_types_int_new(-1); + else + *out = cat_types_int_new((unsigned char)s[i]); + return 0; +} + +static int lf_chr(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + char buf[2]; + + (void)vm; + buf[0] = (char)(nargs > 0 ? cat_types_number_as_int(args[0]) : 0); + buf[1] = '\0'; + *out = cat_types_ascii_text_new(buf); + return 0; +} + +static int lf_substr(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + const char *s; + long long i, n; + char *buf; + + (void)vm; + if (nargs < 3) { + *out = cat_types_ascii_text_new(""); + return 0; + } + s = cat_types_text_bytes(args[0]); + i = cat_types_number_as_int(args[1]); + n = cat_types_number_as_int(args[2]); + if (i < 0 || i > (long long)strlen(s) || n < 0) { + *out = cat_types_ascii_text_new(""); + return 0; + } + buf = malloc((size_t)n + 1); + if (buf == NULL) { + *out = cat_types_ascii_text_new(""); + return 0; + } + memcpy(buf, s + i, (size_t)n); + buf[n] = '\0'; + *out = cat_types_ascii_text_new(buf); + free(buf); + return 0; +} + +static int lf_dofile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + FILE *f; + long sz; + char *src; + CAT_BYTECODE_Function *fn; + CAT_ERROR_Error e; + + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + f = fopen(cat_types_text_bytes(args[0]), "rb"); + if (f == NULL) { + *out = cat_types_nil_get(); + return 0; + } + fseek(f, 0, SEEK_END); + sz = ftell(f); + fseek(f, 0, SEEK_SET); + src = malloc((size_t)sz + 1); + if (src == NULL) { + fclose(f); + *out = cat_types_nil_get(); + return 0; + } + if (fread(src, 1, (size_t)sz, f) != (size_t)sz) { /* short read ok */ } + src[sz] = '\0'; + fclose(f); + cat_error_clear(&e); + fn = cat_compiler_compile(src, &e); + free(src); + if (fn == NULL) { + fprintf(stderr, "dofile: %s\n", e.message); + *out = cat_types_nil_get(); + return 0; + } + cat_error_clear(&e); + cat_vm_run(vm, fn, out); + /* The compiled chunk is intentionally NOT freed: any `function` + * definitions in it became globals whose closures point into this + * bytecode tree. The chunk lives as long as the VM does. */ + return 0; +} + +static int lf_abstractfile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + /* AbstractFile cannot be instantiated: it is the abstract base of the + * stream family (File/StringIO/BytesIO). */ + (void)vm; + (void)args; + (void)nargs; + fprintf(stderr, "AbstractFile is abstract; use File::open, " + "StringIO or BytesIO\n"); + *out = cat_types_nil_get(); + return 0; +} + +static int lf_stringio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + (void)vm; + *out = cat_types_file_stringio(nargs > 0 ? + cat_types_text_bytes(args[0]) : ""); + return 0; +} + +static int lf_bytesio(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + (void)vm; + (void)args; + (void)nargs; + *out = cat_types_file_bytesio(); + return 0; +} + +int cat_stdlib_stdlib_install(CAT_VM_State *vm) +{ + cat_vm_register_native(vm, "print", lf_print); + cat_vm_register_native(vm, "tostring", lf_tostring); + cat_vm_register_native(vm, "tonumber", lf_tonumber); + cat_vm_register_native(vm, "type", lf_type); + cat_vm_register_native(vm, "len", lf_len); + cat_vm_register_native(vm, "toml_parse", lf_toml_parse); + cat_vm_register_native(vm, "toml_encode", lf_toml_encode); + cat_vm_register_native(vm, "read_file", lf_read_file); + cat_vm_register_native(vm, "write_file", lf_write_file); + cat_vm_register_native(vm, "ord", lf_ord); + cat_vm_register_native(vm, "chr", lf_chr); + cat_vm_register_native(vm, "substr", lf_substr); + cat_vm_register_native(vm, "dofile", lf_dofile); + /* the file family: AbstractFile (abstract base), File, StringIO, BytesIO */ + cat_vm_set_global(vm, "AbstractFile", + cat_types_native_new("AbstractFile", lf_abstractfile)); + cat_vm_set_global(vm, "File", cat_types_file_class_table()); + cat_vm_set_global(vm, "StringIO", + cat_types_native_new("StringIO", lf_stringio)); + cat_vm_set_global(vm, "BytesIO", + cat_types_native_new("BytesIO", lf_bytesio)); + return 0; +} diff --git a/src/cat/stdlib/toml.c b/src/cat/stdlib/toml.c new file mode 100644 index 0000000..e75fbc1 --- /dev/null +++ b/src/cat/stdlib/toml.c @@ -0,0 +1,408 @@ +/* + * cat/stdlib/toml.c -- TOML subset parser/encoder. + * + * Naming rule: symbols here are cat_stdlib_toml_* / CAT_STDLIB_TOML_*. + * + * Supported: bare/quoted keys, [table], [[array of tables]], strings, + * integers, floats, booleans, inline arrays, dotted keys. Returns a + * table value so TOML documents are ordinary catscript objects. + */ +#include "cat/stdlib/toml.h" +#include "cat/types/table.h" +#include "cat/types/number.h" +#include "cat/types/text.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/ascii_text.h" +#include "cat/types/bool.h" +#include "cat/types/nil.h" + +#include +#include +#include +#include + +typedef struct { + const char *s; + size_t pos; + int line; + CAT_ERROR_Error *err; +} TParser; + +static void skip_ws(TParser *p) +{ + for (;;) { + char c = p->s[p->pos]; + if (c == ' ' || c == '\t' || c == '\r') { + p->pos++; + } else if (c == '#' || (c == '\n')) { + if (c == '#') { + while (p->s[p->pos] != '\n' && p->s[p->pos] != '\0') + p->pos++; + } else { + p->pos++; + p->line++; + } + } else { + + break; + } + } +} + +static void skip_inline_ws(TParser *p) +{ + while (p->s[p->pos] == ' ' || p->s[p->pos] == '\t') + p->pos++; +} + +static char *parse_key(TParser *p) +{ + char buf[256]; + int n = 0; + + skip_inline_ws(p); + if (p->s[p->pos] == '"') { + p->pos++; + while (p->s[p->pos] != '"' && p->s[p->pos] != '\0') { + if (n < (int)sizeof(buf) - 1) + buf[n++] = p->s[p->pos]; + p->pos++; + } + if (p->s[p->pos] == '"') + p->pos++; + } else { + while (isalnum((unsigned char)p->s[p->pos]) || + p->s[p->pos] == '_' || p->s[p->pos] == '-') { + if (n < (int)sizeof(buf) - 1) + buf[n++] = p->s[p->pos]; + p->pos++; + } + } + buf[n] = '\0'; + return strdup(buf); +} + +static CAT_VALUE_Value *parse_value(TParser *p); + +static CAT_VALUE_Value *parse_string(TParser *p) +{ + char buf[1024]; + int n = 0; + char quote = p->s[p->pos++]; + + while (p->s[p->pos] != quote && p->s[p->pos] != '\0') { + char c = p->s[p->pos++]; + if (c == '\\') { + char e = p->s[p->pos++]; + switch (e) { + case 'n': c = '\n'; break; + case 't': c = '\t'; break; + case 'r': c = '\r'; break; + case '\\': c = '\\'; break; + case '"': c = '"'; break; + default: c = e; break; + } + } + if (n < (int)sizeof(buf) - 1) + buf[n++] = c; + } + if (p->s[p->pos] == quote) + p->pos++; + buf[n] = '\0'; + return cat_types_ascii_text_new(buf); +} + +static CAT_VALUE_Value *parse_array(TParser *p) +{ + CAT_VALUE_Value *arr = cat_types_table_new(); + int idx = 0; + + p->pos++; /* [ */ + for (;;) { + char key[32]; + CAT_VALUE_Value *v; + CAT_ERROR_Error e; + + skip_ws(p); + if (p->s[p->pos] == ']') { + p->pos++; + break; + } + if (p->s[p->pos] == '\0') + break; + v = parse_value(p); + snprintf(key, sizeof(key), "%d", idx++); + cat_error_clear(&e); + cat_types_table_set(arr, key, v, &e); + skip_ws(p); + if (p->s[p->pos] == ',') + p->pos++; + } + return arr; +} + +static CAT_VALUE_Value *parse_value(TParser *p) +{ + char c; + + skip_inline_ws(p); + c = p->s[p->pos]; + + if (c == '"' || c == '\'') + return parse_string(p); + if (c == '[') + return parse_array(p); + if (c == 't' && strncmp(p->s + p->pos, "true", 4) == 0) { + p->pos += 4; + return cat_types_bool_true(); + } + if (c == 'f' && strncmp(p->s + p->pos, "false", 5) == 0) { + p->pos += 5; + return cat_types_bool_false(); + } + if (isdigit((unsigned char)c) || c == '-' || c == '+') { + char buf[64]; + int n = 0; + int isfloat = 0; + while ((isdigit((unsigned char)p->s[p->pos]) || p->s[p->pos] == '-' || + p->s[p->pos] == '+' || p->s[p->pos] == '.' || + p->s[p->pos] == 'e' || p->s[p->pos] == 'E') && + n < (int)sizeof(buf) - 1) { + if (p->s[p->pos] == '.' || p->s[p->pos] == 'e' || + p->s[p->pos] == 'E') + isfloat = 1; + buf[n++] = p->s[p->pos++]; + } + buf[n] = '\0'; + if (isfloat) + return cat_types_float_new(strtod(buf, NULL)); + return cat_types_int_new(strtoll(buf, NULL, 10)); + } + /* fallback: consume a bare word as a string */ + { + char buf[256]; + int n = 0; + while (p->s[p->pos] != '\0' && p->s[p->pos] != '\n' && + p->s[p->pos] != ',' && p->s[p->pos] != ']' && + n < (int)sizeof(buf) - 1) + buf[n++] = p->s[p->pos++]; + buf[n] = '\0'; + return cat_types_ascii_text_new(buf); + } +} + +/* Navigate/create a nested table by dotted path. */ +static CAT_VALUE_Value *descend(CAT_VALUE_Value *root, char *path) +{ + char *save = NULL; + char *part = strtok_r(path, ".", &save); + CAT_VALUE_Value *cur = root; + + while (part != NULL) { + CAT_VALUE_Value *next = NULL; + CAT_ERROR_Error e; + cat_error_clear(&e); + if (cat_types_table_get(cur, part, &next, &e) != 0) { + next = cat_types_table_new(); + cat_error_clear(&e); + cat_types_table_set(cur, part, next, &e); + } + cur = next; + part = strtok_r(NULL, ".", &save); + } + return cur; +} + +int cat_stdlib_toml_parse(const char *text, CAT_VALUE_Value **out, + CAT_ERROR_Error *err) +{ + TParser p; + CAT_VALUE_Value *root = cat_types_table_new(); + CAT_VALUE_Value *current = root; + + p.s = text ? text : ""; + p.pos = 0; + p.line = 1; + p.err = err; + + for (;;) { + skip_ws(&p); + if (p.s[p.pos] == '\0') + break; + + if (p.s[p.pos] == '[') { + int array_table = 0; + char path[256]; + int n = 0; + p.pos++; + if (p.s[p.pos] == '[') { + array_table = 1; + p.pos++; + } + while (p.s[p.pos] != ']' && p.s[p.pos] != '\0' && + n < (int)sizeof(path) - 1) + path[n++] = p.s[p.pos++]; + path[n] = '\0'; + /* trim */ + while (n > 0 && (path[n - 1] == ' ' || path[n - 1] == '\t')) + path[--n] = '\0'; + if (p.s[p.pos] == ']') + p.pos++; + if (p.s[p.pos] == ']') + p.pos++; + if (array_table) { + CAT_VALUE_Value *tbl = cat_types_table_new(); + CAT_ERROR_Error e; + char countkey[32]; + CAT_VALUE_Value *arr = NULL; + int cnt; + cat_error_clear(&e); + if (cat_types_table_get(root, path, &arr, &e) != 0) { + arr = cat_types_table_new(); + cat_error_clear(&e); + cat_types_table_set(root, path, arr, &e); + } + cnt = cat_types_table_count(arr); + snprintf(countkey, sizeof(countkey), "%d", cnt); + cat_error_clear(&e); + cat_types_table_set(arr, countkey, tbl, &e); + current = tbl; + } else { + char copy[256]; + snprintf(copy, sizeof(copy), "%s", path); + current = descend(root, copy); + } + continue; + } + + /* key = value */ + { + char copy[256]; + char *key = parse_key(&p); + CAT_VALUE_Value *val; + CAT_VALUE_Value *target; + CAT_ERROR_Error e; + + snprintf(copy, sizeof(copy), "%s", key); + free(key); + skip_inline_ws(&p); + if (p.s[p.pos] == '=') { + p.pos++; + } else { + /* skip line */ + while (p.s[p.pos] != '\n' && p.s[p.pos] != '\0') + p.pos++; + continue; + } + val = parse_value(&p); + target = descend(current, copy); + cat_error_clear(&e); + /* descend with a full path only makes sense for top-level; + * here `copy` may contain dots for dotted keys. */ + (void)target; + { + char *dot = strrchr(copy, '.'); + if (dot != NULL) { + *dot = '\0'; + descend(current, copy); + cat_error_clear(&e); + cat_types_table_set(descend(current, copy), + dot + 1, val, &e); + } else { + cat_error_clear(&e); + cat_types_table_set(current, copy, val, &e); + } + } + } + } + + *out = root; + return 0; +} + +/* ---- encoder --------------------------------------------------------- */ + +static void enc_value(FILE *f, CAT_VALUE_Value *v); + +static int is_bare_key(const char *s) +{ + if (*s == '\0') + return 0; + for (; *s != '\0'; s++) + if (!(isalnum((unsigned char)*s) || *s == '_' || *s == '-')) + return 0; + return 1; +} + +static void enc_string(FILE *f, const char *s) +{ + fputc('"', f); + for (; *s != '\0'; s++) { + switch (*s) { + case '"': fputs("\\\"", f); break; + case '\\': fputs("\\\\", f); break; + case '\n': fputs("\\n", f); break; + case '\t': fputs("\\t", f); break; + default: fputc(*s, f); break; + } + } + fputc('"', f); +} + +static void enc_value(FILE *f, CAT_VALUE_Value *v) +{ + if (v == NULL || v == cat_types_nil_get()) { + fputs("\"nil\"", f); + } else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) { + enc_string(f, cat_value_type_name(v) ? ((CAT_TYPES_TEXT_Text *)v)->bytes : ""); + } else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { + CAT_TYPES_NUMBER_Number *n = (CAT_TYPES_NUMBER_Number *)v; + if (n->is_float) + fprintf(f, "%g", n->f); + else + fprintf(f, "%lld", n->i); + } else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) { + fputs(((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false", f); + } else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TABLE) { + int i, n = cat_types_table_count(v); + fputc('[', f); + for (i = 0; i < n; i++) { + if (i) + fputs(", ", f); + enc_value(f, cat_types_table_value_at(v, i)); + } + fputc(']', f); + } else { + fputs("\"?\"", f); + } +} + +char *cat_stdlib_toml_encode(CAT_VALUE_Value *tbl, CAT_ERROR_Error *err) +{ + FILE *f; + char *buf; + long sz; + int i, n; + (void)err; + + if (tbl == NULL || !tbl->vtable || tbl->vtable->kind != CAT_VALUE_KIND_TABLE) + return strdup(""); + f = open_memstream(&buf, (size_t *)&sz); + if (f == NULL) + return strdup(""); + n = cat_types_table_count(tbl); + for (i = 0; i < n; i++) { + const char *key = cat_types_table_key_at(tbl, i); + CAT_VALUE_Value *v = cat_types_table_value_at(tbl, i); + if (is_bare_key(key)) + fputs(key, f); + else + enc_string(f, key); + fputs(" = ", f); + enc_value(f, v); + fputc('\n', f); + } + fclose(f); + return buf; +} diff --git a/src/cat/types/ascii_text.c b/src/cat/types/ascii_text.c new file mode 100644 index 0000000..8081f97 --- /dev/null +++ b/src/cat/types/ascii_text.c @@ -0,0 +1,52 @@ +/* + * cat/types/ascii_text.c -- the concrete `ascii_text` type. + * + * Naming rule: symbols here are cat_types_ascii_text_*. + */ +#include "cat/types/ascii_text.h" + +#include +#include + +static void ascii_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_ASCII_TEXT_AsciiText *t = (CAT_TYPES_ASCII_TEXT_AsciiText *)self; + free(t->owned); + free(t); +} + +static CAT_VALUE_Vtable g_ascii_vtable = { + .type_name = "ascii_text", + .kind = CAT_VALUE_KIND_TEXT, + .add = { cat_types_text_concat }, + .get_attribute = { cat_types_text_get_attribute }, + .destroy = ascii_destroy, +}; + +CAT_VALUE_Vtable *cat_types_ascii_text_vtable(void) +{ + return &g_ascii_vtable; +} + +CAT_VALUE_Value *cat_types_ascii_text_new(const char *s) +{ + CAT_TYPES_ASCII_TEXT_AsciiText *t; + size_t n; + + if (s == NULL) + s = ""; + n = strlen(s); + t = calloc(1, sizeof(*t)); + if (t == NULL) + return NULL; + t->owned = malloc(n + 1); + if (t->owned == NULL) { + free(t); + return NULL; + } + memcpy(t->owned, s, n + 1); + t->text.base.vtable = &g_ascii_vtable; + t->text.bytes = t->owned; + t->text.len = (int)n; + return &t->text.base; +} diff --git a/src/cat/types/bool.c b/src/cat/types/bool.c new file mode 100644 index 0000000..ba83b19 --- /dev/null +++ b/src/cat/types/bool.c @@ -0,0 +1,35 @@ +/* + * cat/types/bool.c -- the boolean type. + * + * Naming rule: symbols here are cat_types_bool_* / CAT_TYPES_BOOL_*. + */ +#include "cat/types/bool.h" + +static int bool_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err) +{ + (void)err; + return ((CAT_TYPES_BOOL_Bool *)self)->v != 0; +} + +static CAT_VALUE_Vtable g_bool_vtable = { + .type_name = "bool", + .kind = CAT_VALUE_KIND_BOOL, + .truthy = bool_truthy, +}; + +CAT_VALUE_Vtable *cat_types_bool_vtable(void) +{ + return &g_bool_vtable; +} + +CAT_VALUE_Value *cat_types_bool_true(void) +{ + static CAT_TYPES_BOOL_Bool t = { { &g_bool_vtable }, 1 }; + return &t.base; +} + +CAT_VALUE_Value *cat_types_bool_false(void) +{ + static CAT_TYPES_BOOL_Bool f = { { &g_bool_vtable }, 0 }; + return &f.base; +} diff --git a/src/cat/types/byte.c b/src/cat/types/byte.c new file mode 100644 index 0000000..e0e251a --- /dev/null +++ b/src/cat/types/byte.c @@ -0,0 +1,53 @@ +/* + * cat/types/byte.c -- the concrete `byte` type. + * + * Naming rule: symbols here are cat_types_byte_* / CAT_TYPES_BYTE_*. + */ +#include "cat/types/byte.h" + +#include + +static void byte_destroy(CAT_VALUE_Value *self) +{ + free(self); +} + +static int byte_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err) +{ + (void)err; + return ((CAT_TYPES_NUMBER_Number *)self)->i != 0; +} + +static CAT_VALUE_Vtable g_byte_vtable = { + .type_name = "byte", + .kind = CAT_VALUE_KIND_NUMBER, + .add = { cat_types_number_add }, + .sub = { cat_types_number_sub }, + .mul = { cat_types_number_mul }, + .div = { cat_types_number_div }, + .rem = { cat_types_number_rem }, + .call = { NULL }, + .raise = { NULL }, + .get_attribute = { NULL }, + .set_attribute = { NULL }, + .truthy = byte_truthy, + .destroy = byte_destroy, +}; + +CAT_VALUE_Vtable *cat_types_byte_vtable(void) +{ + return &g_byte_vtable; +} + +CAT_VALUE_Value *cat_types_byte_new(unsigned int v) +{ + CAT_TYPES_BYTE_Byte *n = calloc(1, sizeof(*n)); + + if (n == NULL) + return NULL; + n->number.base.vtable = &g_byte_vtable; + n->number.is_float = 0; + n->number.i = (long long)(v & 0xFFu); + n->number.f = (double)(v & 0xFFu); + return &n->number.base; +} diff --git a/src/cat/types/char.c b/src/cat/types/char.c new file mode 100644 index 0000000..4068d24 --- /dev/null +++ b/src/cat/types/char.c @@ -0,0 +1,65 @@ +/* + * cat/types/char.c -- the fixed-width text types char1..char4. + * + * Naming rule: symbols here are cat_types_char_* / CAT_TYPES_CHAR_*. + */ +#include "cat/types/char.h" + +#include +#include + +static void char_destroy(CAT_VALUE_Value *self) +{ + free(self); +} + +/* Four vtables, one per width, so type_name reports e.g. "char2". */ +static CAT_VALUE_Vtable g_char_vtables[4] = { + { .type_name = "char1", .kind = CAT_VALUE_KIND_TEXT, + .add = { cat_types_text_concat }, + .get_attribute = { cat_types_text_get_attribute }, + .destroy = char_destroy }, + { .type_name = "char2", .kind = CAT_VALUE_KIND_TEXT, + .add = { cat_types_text_concat }, + .get_attribute = { cat_types_text_get_attribute }, + .destroy = char_destroy }, + { .type_name = "char3", .kind = CAT_VALUE_KIND_TEXT, + .add = { cat_types_text_concat }, + .get_attribute = { cat_types_text_get_attribute }, + .destroy = char_destroy }, + { .type_name = "char4", .kind = CAT_VALUE_KIND_TEXT, + .add = { cat_types_text_concat }, + .get_attribute = { cat_types_text_get_attribute }, + .destroy = char_destroy }, +}; + +CAT_VALUE_Vtable *cat_types_char_vtable(int width) +{ + if (width < 1) + width = 1; + if (width > 4) + width = 4; + return &g_char_vtables[width - 1]; +} + +CAT_VALUE_Value *cat_types_char_new(int width, const char *s) +{ + CAT_TYPES_CHAR_Char *c; + + if (width < 1 || width > 4) + return NULL; + c = calloc(1, sizeof(*c)); + if (c == NULL) + return NULL; + c->width = width; + if (s != NULL) { + int i; + for (i = 0; i < width && s[i] != '\0'; i++) + c->buf[i] = s[i]; + } + c->buf[width] = '\0'; + c->text.base.vtable = cat_types_char_vtable(width); + c->text.bytes = c->buf; + c->text.len = width; + return &c->text.base; +} diff --git a/src/cat/types/file.c b/src/cat/types/file.c new file mode 100644 index 0000000..f5e15f4 --- /dev/null +++ b/src/cat/types/file.c @@ -0,0 +1,358 @@ +/* + * cat/types/file.c -- the file family (AbstractFile/File/StringIO/BytesIO). + * + * Naming rule: symbols here are cat_types_file_* / CAT_TYPES_FILE_*. + * + * AbstractFile is the abstract base; all streams share one vtable and + * therefore the same method set, so they are interchangeable: + * + * f = File::open("x.txt") -- a real file + * s = StringIO("hello") -- an in-memory text stream + * b = BytesIO() -- an in-memory byte stream + * f:write("data"); f:close() + * s:read() + * + * Thread-safety: every stream owns its own buffer/handle; nothing here + * touches shared mutable state, so streams created and used on separate + * threads never interfere (no GIL). + */ +#include "cat/types/file.h" +#include "cat/types/native.h" +#include "cat/types/int.h" +#include "cat/types/nil.h" +#include "cat/types/ascii_text.h" +#include "cat/types/table.h" +#include "cat/error.h" + +#include +#include +#include + +#define AF(v) ((CAT_TYPES_FILE_AbstractFile *)(v)) + +static const char *as_text(CAT_VALUE_Value *v) +{ + return (v != NULL && v->vtable && + v->vtable->kind == CAT_VALUE_KIND_TEXT) + ? cat_types_text_bytes(v) : NULL; +} + +static long long as_int(CAT_VALUE_Value *v) +{ + return (v != NULL && v->vtable && + v->vtable->kind == CAT_VALUE_KIND_NUMBER) + ? cat_types_number_as_int(v) : 0; +} + +/* ---- methods (self is args[0]) --------------------------------------- */ + +static int m_read(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_TYPES_FILE_AbstractFile *af; + long long want; + + (void)vm; + if (nargs < 1) { + *out = cat_types_nil_get(); + return 0; + } + af = AF(args[0]); + if (af->closed) { + *out = cat_types_nil_get(); + return 0; + } + want = (nargs > 1) ? as_int(args[1]) : -1; + + if (af->is_bytes) { + CAT_TYPES_FILE_MemFile *m = (CAT_TYPES_FILE_MemFile *)af; + long avail = m->len - m->pos; + long take = (want < 0 || want > avail) ? avail : (long)want; + char *buf = malloc((size_t)take + 1); + if (buf == NULL) { + *out = cat_types_nil_get(); + return 0; + } + memcpy(buf, m->buf + m->pos, (size_t)take); + buf[take] = '\0'; + m->pos += take; + *out = cat_types_ascii_text_new(buf); + free(buf); + return 0; + } else { + CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af; + size_t cap = 256, n = 0; + char *buf = malloc(cap); + FILE *fp = (FILE *)f->fp; + if (buf == NULL) { + *out = cat_types_nil_get(); + return 0; + } + for (;;) { + int ch = fgetc(fp); + if (ch == EOF) + break; + if (want >= 0 && (long long)n >= want) + break; + if (n + 1 >= cap) { + cap *= 2; + buf = realloc(buf, cap); + if (buf == NULL) + break; + } + buf[n++] = (char)ch; + } + buf[n] = '\0'; + *out = cat_types_ascii_text_new(buf); + free(buf); + return 0; + } +} + +static int m_write(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_TYPES_FILE_AbstractFile *af; + const char *s; + + (void)vm; + if (nargs < 2) { + *out = cat_types_int_new(0); + return 0; + } + af = AF(args[0]); + s = as_text(args[1]); + if (af->closed || s == NULL) { + *out = cat_types_int_new(0); + return 0; + } + if (af->is_bytes) { + CAT_TYPES_FILE_MemFile *m = (CAT_TYPES_FILE_MemFile *)af; + size_t add = strlen(s); + if (m->len + (long)add + 1 > m->cap) { + long nc = (m->cap ? m->cap : 128); + while (nc < m->len + (long)add + 1) + nc *= 2; + m->buf = realloc(m->buf, (size_t)nc); + m->cap = nc; + } + memcpy(m->buf + m->len, s, add); + m->len += (long)add; + m->buf[m->len] = '\0'; + *out = cat_types_int_new((long long)add); + return 0; + } else { + CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af; + size_t w = fwrite(s, 1, strlen(s), (FILE *)f->fp); + fflush((FILE *)f->fp); + *out = cat_types_int_new((long long)w); + return 0; + } +} + +static int m_close(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_TYPES_FILE_AbstractFile *af; + + (void)vm; + if (nargs >= 1) { + af = AF(args[0]); + if (!af->closed && !af->is_bytes) { + CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af; + if (f->fp != NULL) + fclose((FILE *)f->fp); + f->fp = NULL; + } + af->closed = 1; + } + *out = cat_types_nil_get(); + return 0; +} + +static int m_name(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + CAT_TYPES_FILE_AbstractFile *af; + + (void)vm; + if (nargs < 1) { + *out = cat_types_ascii_text_new(""); + return 0; + } + af = AF(args[0]); + if (!af->is_bytes) { + CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af; + *out = cat_types_ascii_text_new(f->path ? f->path : ""); + } else { + *out = cat_types_ascii_text_new(af->is_bytes == 1 ? "" : ""); + } + return 0; +} + +static int file_get_attr(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + (void)self; + (void)err; + if (strcmp(name, "read") == 0) { + *out = cat_types_native_new("read", m_read); + return 0; + } + if (strcmp(name, "write") == 0) { + *out = cat_types_native_new("write", m_write); + return 0; + } + if (strcmp(name, "close") == 0) { + *out = cat_types_native_new("close", m_close); + return 0; + } + if (strcmp(name, "name") == 0) { + *out = cat_types_native_new("name", m_name); + return 0; + } + return (cat_error_raise(err, "file has no method '%s'", name), -1); +} + +static void file_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_FILE_AbstractFile *af = AF(self); + + if (af->is_bytes) { + CAT_TYPES_FILE_MemFile *m = (CAT_TYPES_FILE_MemFile *)af; + free(m->buf); + } else { + CAT_TYPES_FILE_File *f = (CAT_TYPES_FILE_File *)af; + if (!af->closed && f->fp != NULL) + fclose((FILE *)f->fp); + free(f->path); + } + free(self); +} + +static CAT_VALUE_Vtable g_file_vtable = { + .type_name = "File", + .kind = CAT_VALUE_KIND_TABLE, + .get_attribute = { file_get_attr }, + .destroy = file_destroy, +}; + +CAT_VALUE_Vtable *cat_types_file_abstract_vtable(void) +{ + return &g_file_vtable; +} + +/* ---- constructors ---------------------------------------------------- */ + +CAT_VALUE_Value *cat_types_file_open(const char *path, const char *mode) +{ + CAT_TYPES_FILE_File *f; + FILE *fp; + int m = 0; + + if (path == NULL) + return cat_types_nil_get(); + if (mode == NULL) + mode = "r"; + fp = fopen(path, mode); + if (fp == NULL) + return cat_types_nil_get(); + if (strchr(mode, 'w') != NULL) + m = CAT_TYPES_FILE_MODE_WRITE; + else if (strchr(mode, 'a') != NULL) + m = CAT_TYPES_FILE_MODE_APPEND; + else + m = CAT_TYPES_FILE_MODE_READ; + f = calloc(1, sizeof(*f)); + if (f == NULL) { + fclose(fp); + return cat_types_nil_get(); + } + f->af.base.vtable = &g_file_vtable; + f->af.mode = m; + f->af.closed = 0; + f->af.is_bytes = 0; + f->fp = fp; + f->path = strdup(path); + return &f->af.base; +} + +CAT_VALUE_Value *cat_types_file_stringio(const char *initial) +{ + CAT_TYPES_FILE_MemFile *m = calloc(1, sizeof(*m)); + + if (m == NULL) + return cat_types_nil_get(); + m->af.base.vtable = &g_file_vtable; + m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE; + m->af.is_bytes = 1; /* in-memory */ + m->cap = 128; + m->buf = malloc((size_t)m->cap); + if (m->buf == NULL) { + free(m); + return cat_types_nil_get(); + } + m->buf[0] = '\0'; + if (initial != NULL) { + size_t n = strlen(initial); + if ((long)n + 1 > m->cap) { + m->cap = (long)n + 1; + m->buf = realloc(m->buf, (size_t)m->cap); + } + memcpy(m->buf, initial, n + 1); + m->len = (long)n; + } + m->pos = 0; + m->af.is_bytes = 3; /* 3 == StringIO text marker */ + return &m->af.base; +} + +CAT_VALUE_Value *cat_types_file_bytesio(void) +{ + CAT_TYPES_FILE_MemFile *m = calloc(1, sizeof(*m)); + + if (m == NULL) + return cat_types_nil_get(); + m->af.base.vtable = &g_file_vtable; + m->af.mode = CAT_TYPES_FILE_MODE_READ | CAT_TYPES_FILE_MODE_WRITE; + m->cap = 128; + m->buf = malloc((size_t)m->cap); + if (m->buf == NULL) { + free(m); + return cat_types_nil_get(); + } + m->buf[0] = '\0'; + m->pos = 0; + m->af.is_bytes = 2; /* 2 == BytesIO marker */ + return &m->af.base; +} + +/* ---- the class table: File::open(...) -------------------------------- */ + +static int cm_open(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out) +{ + const char *path, *mode; + + (void)vm; + if (nargs < 2) { + *out = cat_types_nil_get(); + return 0; + } + path = as_text(args[1]); + mode = (nargs > 2) ? as_text(args[2]) : "r"; + if (mode == NULL) + mode = "r"; + *out = cat_types_file_open(path, mode); + return 0; +} + +CAT_VALUE_Value *cat_types_file_class_table(void) +{ + CAT_VALUE_Value *t = cat_types_table_new(); + CAT_ERROR_Error e; + + cat_error_clear(&e); + cat_types_table_set(t, "open", cat_types_native_new("open", cm_open), &e); + return t; +} diff --git a/src/cat/types/float.c b/src/cat/types/float.c new file mode 100644 index 0000000..c0146f1 --- /dev/null +++ b/src/cat/types/float.c @@ -0,0 +1,53 @@ +/* + * cat/types/float.c -- the concrete `float` type. + * + * Naming rule: symbols here are cat_types_float_* / CAT_TYPES_FLOAT_*. + */ +#include "cat/types/float.h" + +#include + +static void float_destroy(CAT_VALUE_Value *self) +{ + free(self); +} + +static int float_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err) +{ + (void)err; + return ((CAT_TYPES_NUMBER_Number *)self)->f != 0.0; +} + +static CAT_VALUE_Vtable g_float_vtable = { + .type_name = "float", + .kind = CAT_VALUE_KIND_NUMBER, + .add = { cat_types_number_add }, + .sub = { cat_types_number_sub }, + .mul = { cat_types_number_mul }, + .div = { cat_types_number_div }, + .rem = { cat_types_number_rem }, + .call = { NULL }, + .raise = { NULL }, + .get_attribute = { NULL }, + .set_attribute = { NULL }, + .truthy = float_truthy, + .destroy = float_destroy, +}; + +CAT_VALUE_Vtable *cat_types_float_vtable(void) +{ + return &g_float_vtable; +} + +CAT_VALUE_Value *cat_types_float_new(double v) +{ + CAT_TYPES_FLOAT_Float *n = calloc(1, sizeof(*n)); + + if (n == NULL) + return NULL; + n->number.base.vtable = &g_float_vtable; + n->number.is_float = 1; + n->number.f = v; + n->number.i = (long long)v; + return &n->number.base; +} diff --git a/src/cat/types/function.c b/src/cat/types/function.c new file mode 100644 index 0000000..56e5829 --- /dev/null +++ b/src/cat/types/function.c @@ -0,0 +1,61 @@ +/* + * cat/types/function.c -- closures. + * + * Naming rule: symbols here are cat_types_function_*. + * + * Calling a closure enters the VM (cat_vm_exec_closure). The compiler + * emits OP_CALL on any value and this type's call slot is what runs the + * subroutine, keeping "everything is an object" honest. + */ +#include "cat/types/function.h" +#include "cat/vm.h" + +#include + +int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, + CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out); + +static int function_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, + int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self; + /* The active VM for this thread (thread-local, so no global lock). */ + CAT_VM_State *vm = cat_vm_current(); + (void)err; + if (vm == NULL) + return (cat_error_raise(err, "no active VM"), -1); + return cat_vm_exec_closure(vm, cl, args, nargs, out); +} + +static void function_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_FUNCTION_Closure *cl = (CAT_TYPES_FUNCTION_Closure *)self; + free(cl->upvals); + /* proto is owned by its enclosing module/bytecode tree */ + free(cl); +} + +static CAT_VALUE_Vtable g_function_vtable = { + .type_name = "function", + .kind = CAT_VALUE_KIND_FUNCTION, + .call = { function_call }, + .destroy = function_destroy, +}; + +CAT_VALUE_Vtable *cat_types_function_vtable(void) +{ + return &g_function_vtable; +} + +CAT_VALUE_Value *cat_types_function_new(CAT_BYTECODE_Function *proto) +{ + CAT_TYPES_FUNCTION_Closure *cl = calloc(1, sizeof(*cl)); + + if (cl == NULL) + return NULL; + cl->base.vtable = &g_function_vtable; + cl->proto = proto; + cl->nupvals = 0; + cl->upvals = NULL; + return &cl->base; +} diff --git a/src/cat/types/int.c b/src/cat/types/int.c new file mode 100644 index 0000000..a65cd72 --- /dev/null +++ b/src/cat/types/int.c @@ -0,0 +1,53 @@ +/* + * cat/types/int.c -- the concrete `int` type. + * + * Naming rule: symbols here are cat_types_int_* / CAT_TYPES_INT_*. + */ +#include "cat/types/int.h" + +#include + +static void int_destroy(CAT_VALUE_Value *self) +{ + free(self); +} + +static int int_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err) +{ + (void)err; + return ((CAT_TYPES_NUMBER_Number *)self)->i != 0; +} + +static CAT_VALUE_Vtable g_int_vtable = { + .type_name = "int", + .kind = CAT_VALUE_KIND_NUMBER, + .add = { cat_types_number_add }, + .sub = { cat_types_number_sub }, + .mul = { cat_types_number_mul }, + .div = { cat_types_number_div }, + .rem = { cat_types_number_rem }, + .call = { NULL }, + .raise = { NULL }, + .get_attribute = { NULL }, + .set_attribute = { NULL }, + .truthy = int_truthy, + .destroy = int_destroy, +}; + +CAT_VALUE_Vtable *cat_types_int_vtable(void) +{ + return &g_int_vtable; +} + +CAT_VALUE_Value *cat_types_int_new(long long v) +{ + CAT_TYPES_INT_Int *n = calloc(1, sizeof(*n)); + + if (n == NULL) + return NULL; + n->number.base.vtable = &g_int_vtable; + n->number.is_float = 0; + n->number.i = v; + n->number.f = (double)v; + return &n->number.base; +} diff --git a/src/cat/types/native.c b/src/cat/types/native.c new file mode 100644 index 0000000..1e7fe17 --- /dev/null +++ b/src/cat/types/native.c @@ -0,0 +1,59 @@ +/* + * cat/types/native.c -- native function values. + * + * Naming rule: symbols here are cat_types_native_* / CAT_TYPES_NATIVE_*. + */ +#include "cat/types/native.h" +#include "cat/vm.h" +#include "cat/error.h" + +#include +#include + +static int native_call(CAT_VALUE_Value *self, CAT_VALUE_Value **args, + int nargs, CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self; + CAT_VM_State *vm = cat_vm_current(); + + if (vm == NULL) + return (cat_error_raise(err, "no active VM"), -1); + return nf->cb(vm, args, nargs, out); +} + +static void native_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_NATIVE_Native *nf = (CAT_TYPES_NATIVE_Native *)self; + free(nf->name); + free(nf); +} + +static CAT_VALUE_Vtable g_native_vtable = { + .type_name = "native", + .kind = CAT_VALUE_KIND_FUNCTION, + .call = { native_call }, + .destroy = native_destroy, +}; + +CAT_VALUE_Vtable *cat_types_native_vtable(void) +{ + return &g_native_vtable; +} + +CAT_VALUE_Value *cat_types_native_new(const char *name, + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, CAT_VALUE_Value **)) +{ + CAT_TYPES_NATIVE_Native *nf = calloc(1, sizeof(*nf)); + + if (nf == NULL) + return NULL; + nf->base.vtable = &g_native_vtable; + nf->name = strdup(name ? name : "native"); + nf->cb = cb; + return &nf->base; +} + +int cat_types_native_is(CAT_VALUE_Value *v) +{ + return v != NULL && v->vtable == &g_native_vtable; +} diff --git a/src/cat/types/nil.c b/src/cat/types/nil.c new file mode 100644 index 0000000..05b500b --- /dev/null +++ b/src/cat/types/nil.c @@ -0,0 +1,31 @@ +/* + * cat/types/nil.c -- the `nil` singleton value. + * + * Naming rule: symbols here are cat_types_nil_* / CAT_TYPES_NIL_*. + */ +#include "cat/types/nil.h" + +static int nil_truthy(CAT_VALUE_Value *self, CAT_ERROR_Error *err) +{ + (void)self; + (void)err; + return 0; /* nil is falsy */ +} + +static CAT_VALUE_Vtable g_nil_vtable = { + .type_name = "nil", + .kind = CAT_VALUE_KIND_NIL, + .truthy = nil_truthy, +}; + +CAT_VALUE_Vtable *cat_types_nil_vtable(void) +{ + return &g_nil_vtable; +} + +CAT_VALUE_Value *cat_types_nil_get(void) +{ + static CAT_TYPES_NIL_Nil g_nil; + g_nil.base.vtable = &g_nil_vtable; + return &g_nil.base; +} diff --git a/src/cat/types/number.c b/src/cat/types/number.c new file mode 100644 index 0000000..b743469 --- /dev/null +++ b/src/cat/types/number.c @@ -0,0 +1,122 @@ +/* + * cat/types/number.c -- shared numeric semantics for Cat_Number. + * + * Naming rule: symbols here are cat_types_number_* / CAT_TYPES_NUMBER_*. + * The compiler/VM does NOT own arithmetic: every +,-,*,/,% on numbers + * lands here, so embedders and the language share one implementation. + */ +#include "cat/types/number.h" +#include "cat/types/int.h" +#include "cat/types/float.h" + +#include +#include + +static CAT_TYPES_NUMBER_Number *as_num(CAT_VALUE_Value *v) +{ + return (CAT_TYPES_NUMBER_Number *)v; +} + +int cat_types_number_is_number(CAT_VALUE_Value *v) +{ + return v != NULL && v->vtable != NULL && + v->vtable->kind == CAT_VALUE_KIND_NUMBER; +} + +double cat_types_number_as_double(CAT_VALUE_Value *v) +{ + CAT_TYPES_NUMBER_Number *n = as_num(v); + return n->is_float ? n->f : (double)n->i; +} + +long long cat_types_number_as_int(CAT_VALUE_Value *v) +{ + CAT_TYPES_NUMBER_Number *n = as_num(v); + return n->is_float ? (long long)n->f : n->i; +} + +/* Build a result number: float if either side is float, else int. */ +static CAT_VALUE_Value *make_result(int want_float, long long iv, double fv) +{ + if (want_float) + return cat_types_float_new(fv); + return cat_types_int_new(iv); +} + +int cat_types_number_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + int wf; + if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b)) + return (cat_error_raise(err, "add expects numbers"), -1); + wf = as_num(a)->is_float || as_num(b)->is_float; + *out = make_result(wf, (long long)(cat_types_number_as_double(a) + + cat_types_number_as_double(b)), + cat_types_number_as_double(a) + + cat_types_number_as_double(b)); + return 0; +} + +int cat_types_number_sub(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + int wf; + if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b)) + return (cat_error_raise(err, "sub expects numbers"), -1); + wf = as_num(a)->is_float || as_num(b)->is_float; + *out = make_result(wf, (long long)(cat_types_number_as_double(a) - + cat_types_number_as_double(b)), + cat_types_number_as_double(a) - + cat_types_number_as_double(b)); + return 0; +} + +int cat_types_number_mul(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + int wf; + if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b)) + return (cat_error_raise(err, "mul expects numbers"), -1); + wf = as_num(a)->is_float || as_num(b)->is_float; + *out = make_result(wf, (long long)(cat_types_number_as_double(a) * + cat_types_number_as_double(b)), + cat_types_number_as_double(a) * + cat_types_number_as_double(b)); + return 0; +} + +int cat_types_number_div(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + double d; + if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b)) + return (cat_error_raise(err, "div expects numbers"), -1); + d = cat_types_number_as_double(b); + if (d == 0.0) + return (cat_error_raise(err, "division by zero"), -1); + /* division always yields float, matching Lua's `/`. */ + *out = cat_types_float_new(cat_types_number_as_double(a) / d); + return 0; +} + +int cat_types_number_rem(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + double d; + int wf; + if (!cat_types_number_is_number(a) || !cat_types_number_is_number(b)) + return (cat_error_raise(err, "rem expects numbers"), -1); + wf = as_num(a)->is_float || as_num(b)->is_float; + if (wf) { + d = cat_types_number_as_double(b); + if (d == 0.0) + return (cat_error_raise(err, "modulo by zero"), -1); + *out = cat_types_float_new(fmod(cat_types_number_as_double(a), d)); + } else { + long long ib = cat_types_number_as_int(b); + if (ib == 0) + return (cat_error_raise(err, "modulo by zero"), -1); + *out = cat_types_int_new(cat_types_number_as_int(a) % ib); + } + return 0; +} diff --git a/src/cat/types/table.c b/src/cat/types/table.c new file mode 100644 index 0000000..a4017ff --- /dev/null +++ b/src/cat/types/table.c @@ -0,0 +1,136 @@ +/* + * cat/types/table.c -- the table/object type. + * + * Naming rule: symbols here are cat_types_table_* / CAT_TYPES_TABLE_*. + */ +#include "cat/types/table.h" +#include "cat/types/text.h" +#include "cat/types/ascii_text.h" + +#include +#include + +static int table_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_ERROR_Error local; + CAT_VALUE_Value *base = NULL; + + cat_error_clear(&local); + if (cat_types_table_get(self, name, out, &local) == 0) + return 0; + /* Inheritance: a `__index` attribute names a base table/method table. + * Looking the key up there gives lightweight class inheritance, so a + * concrete class (e.g. `File`) can share methods with its abstract + * base (`AbstractFile`). */ + cat_error_clear(&local); + if (cat_types_table_get(self, "__index", &base, &local) == 0 && + base != NULL && base != self) + return cat_value_get_attribute(base, name, out, err); + return (cat_error_raise(err, "table has no key '%s'", name), -1); +} + +static int table_set_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value *value, CAT_ERROR_Error *err) +{ + return cat_types_table_set(self, name, value, err); +} + +static void table_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)self; + int i; + /* Values are NOT destroyed: the same value object may be referenced + * from several tables (globals, constants, locals), so a recursive + * destroy would double-free. We only release the table's own keys + * and storage. */ + for (i = 0; i < t->npairs; i++) + free(t->pairs[i].key); + free(t->pairs); + free(t); +} + +static CAT_VALUE_Vtable g_table_vtable = { + .type_name = "table", + .kind = CAT_VALUE_KIND_TABLE, + .get_attribute = { table_get_attribute }, + .set_attribute = { table_set_attribute }, + .destroy = table_destroy, +}; + +CAT_VALUE_Vtable *cat_types_table_vtable(void) +{ + return &g_table_vtable; +} + +CAT_VALUE_Value *cat_types_table_new(void) +{ + CAT_TYPES_TABLE_Table *t = calloc(1, sizeof(*t)); + + if (t == NULL) + return NULL; + t->base.vtable = &g_table_vtable; + return &t->base; +} + +static int find_key(CAT_TYPES_TABLE_Table *t, const char *key) +{ + int i; + for (i = 0; i < t->npairs; i++) + if (strcmp(t->pairs[i].key, key) == 0) + return i; + return -1; +} + +int cat_types_table_set(CAT_VALUE_Value *tbl, const char *key, + CAT_VALUE_Value *value, CAT_ERROR_Error *err) +{ + CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)tbl; + int idx = find_key(t, key); + + (void)err; + if (idx >= 0) { + t->pairs[idx].value = value; + return 0; + } + if (t->npairs == t->cappairs) { + int nc = t->cappairs ? t->cappairs * 2 : 4; + CAT_TYPES_TABLE_Pair *np = realloc(t->pairs, (size_t)nc * sizeof(*np)); + if (np == NULL) + return (cat_error_raise(err, "out of memory"), -1); + t->pairs = np; + t->cappairs = nc; + } + t->pairs[t->npairs].key = strdup(key); + t->pairs[t->npairs].value = value; + t->npairs++; + return 0; +} + +int cat_types_table_get(CAT_VALUE_Value *tbl, const char *key, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_TABLE_Table *t = (CAT_TYPES_TABLE_Table *)tbl; + int idx = find_key(t, key); + + if (idx >= 0) { + *out = t->pairs[idx].value; + return 0; + } + return (cat_error_raise(err, "table has no key '%s'", key), -1); +} + +int cat_types_table_count(CAT_VALUE_Value *tbl) +{ + return ((CAT_TYPES_TABLE_Table *)tbl)->npairs; +} + +const char *cat_types_table_key_at(CAT_VALUE_Value *tbl, int i) +{ + return ((CAT_TYPES_TABLE_Table *)tbl)->pairs[i].key; +} + +CAT_VALUE_Value *cat_types_table_value_at(CAT_VALUE_Value *tbl, int i) +{ + return ((CAT_TYPES_TABLE_Table *)tbl)->pairs[i].value; +} diff --git a/src/cat/types/text.c b/src/cat/types/text.c new file mode 100644 index 0000000..3988747 --- /dev/null +++ b/src/cat/types/text.c @@ -0,0 +1,64 @@ +/* + * cat/types/text.c -- shared text semantics for Cat_Text. + * + * Naming rule: symbols here are cat_types_text_* / CAT_TYPES_TEXT_*. + * Concatenation and the `length` attribute live here, shared by every + * concrete text type (charN, ascii_text, utf8_text). + */ +#include "cat/types/text.h" +#include "cat/types/ascii_text.h" +#include "cat/types/int.h" + +#include +#include + +const char *cat_types_text_bytes(CAT_VALUE_Value *v) +{ + CAT_TYPES_TEXT_Text *t = (CAT_TYPES_TEXT_Text *)v; + return t->bytes ? t->bytes : ""; +} + +int cat_types_text_length(CAT_VALUE_Value *v) +{ + CAT_TYPES_TEXT_Text *t = (CAT_TYPES_TEXT_Text *)v; + return t->len; +} + +int cat_types_text_is_text(CAT_VALUE_Value *v) +{ + return v != NULL && v->vtable != NULL && + v->vtable->kind == CAT_VALUE_KIND_TEXT; +} + +int cat_types_text_concat(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + size_t la, lb; + char *buf; + CAT_VALUE_Value *r; + + if (!cat_types_text_is_text(a) || !cat_types_text_is_text(b)) + return (cat_error_raise(err, "concat expects text"), -1); + la = strlen(cat_types_text_bytes(a)); + lb = strlen(cat_types_text_bytes(b)); + buf = malloc(la + lb + 1); + if (buf == NULL) + return (cat_error_raise(err, "out of memory"), -1); + memcpy(buf, cat_types_text_bytes(a), la); + memcpy(buf + la, cat_types_text_bytes(b), lb); + buf[la + lb] = '\0'; + r = cat_types_ascii_text_new(buf); + free(buf); + *out = r; + return 0; +} + +int cat_types_text_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (strcmp(name, "length") == 0 || strcmp(name, "len") == 0) { + *out = cat_types_int_new(cat_types_text_length(self)); + return 0; + } + return (cat_error_raise(err, "text has no attribute '%s'", name), -1); +} diff --git a/src/cat/types/utf8_text.c b/src/cat/types/utf8_text.c new file mode 100644 index 0000000..3c914cb --- /dev/null +++ b/src/cat/types/utf8_text.c @@ -0,0 +1,75 @@ +/* + * cat/types/utf8_text.c -- the concrete `utf8_text` type. + * + * Naming rule: symbols here are cat_types_utf8_text_*. + * `length` counts Unicode code points (not bytes), unlike ascii_text. + */ +#include "cat/types/utf8_text.h" + +#include +#include + +/* Count UTF-8 code points: a byte not matching 10xxxxxx starts one. */ +static int utf8_count(const char *s) +{ + int n = 0; + for (; *s != '\0'; s++) + if (((unsigned char)*s & 0xC0u) != 0x80u) + n++; + return n; +} + +static int utf8_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + CAT_TYPES_UTF8_TEXT_Utf8Text *t = (CAT_TYPES_UTF8_TEXT_Utf8Text *)self; + extern CAT_VALUE_Value *cat_types_int_new(long long); + if (strcmp(name, "length") == 0 || strcmp(name, "len") == 0) { + *out = cat_types_int_new(utf8_count(t->text.bytes)); + return 0; + } + return (cat_error_raise(err, "utf8_text has no attribute '%s'", name), -1); +} + +static void utf8_destroy(CAT_VALUE_Value *self) +{ + CAT_TYPES_UTF8_TEXT_Utf8Text *t = (CAT_TYPES_UTF8_TEXT_Utf8Text *)self; + free(t->owned); + free(t); +} + +static CAT_VALUE_Vtable g_utf8_vtable = { + .type_name = "utf8_text", + .kind = CAT_VALUE_KIND_TEXT, + .add = { cat_types_text_concat }, + .get_attribute = { utf8_get_attribute }, + .destroy = utf8_destroy, +}; + +CAT_VALUE_Vtable *cat_types_utf8_text_vtable(void) +{ + return &g_utf8_vtable; +} + +CAT_VALUE_Value *cat_types_utf8_text_new(const char *s) +{ + CAT_TYPES_UTF8_TEXT_Utf8Text *t; + size_t n; + + if (s == NULL) + s = ""; + n = strlen(s); + t = calloc(1, sizeof(*t)); + if (t == NULL) + return NULL; + t->owned = malloc(n + 1); + if (t->owned == NULL) { + free(t); + return NULL; + } + memcpy(t->owned, s, n + 1); + t->text.base.vtable = &g_utf8_vtable; + t->text.bytes = t->owned; + t->text.len = (int)n; + return &t->text.base; +} diff --git a/src/cat/value.c b/src/cat/value.c new file mode 100644 index 0000000..0d8ed87 --- /dev/null +++ b/src/cat/value.c @@ -0,0 +1,135 @@ +/* + * cat/value.c -- dispatch helpers over the CAT_VALUE_Vtable. + * + * Naming rule: symbols here are cat_value_* / CAT_VALUE_*. + * + * These helpers implement the "friendly C API": a caller working with + * opaque CAT_VALUE_Value* pointers can perform any operator without + * knowing the concrete type. A missing vtable slot becomes a structured + * error, never a crash. + */ +#include "cat/value.h" +#include "cat/error.h" + +#include +#include + +const char *cat_value_type_name(CAT_VALUE_Value *v) +{ + if (v == NULL || v->vtable == NULL || v->vtable->type_name == NULL) + return ""; + return v->vtable->type_name; +} + +static CAT_VALUE_Vtable *vt(CAT_VALUE_Value *v) +{ + return (v != NULL) ? v->vtable : NULL; +} + +int cat_value_add(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(a) == NULL || vt(a)->add.fn == NULL) + return (cat_error_raise(err, + "type %s does not implement add", cat_value_type_name(a)), -1); + return vt(a)->add.fn(a, b, out, err); +} + +int cat_value_sub(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(a) == NULL || vt(a)->sub.fn == NULL) + return (cat_error_raise(err, + "type %s does not implement sub", cat_value_type_name(a)), -1); + return vt(a)->sub.fn(a, b, out, err); +} + +int cat_value_mul(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(a) == NULL || vt(a)->mul.fn == NULL) + return (cat_error_raise(err, + "type %s does not implement mul", cat_value_type_name(a)), -1); + return vt(a)->mul.fn(a, b, out, err); +} + +int cat_value_div(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(a) == NULL || vt(a)->div.fn == NULL) + return (cat_error_raise(err, + "type %s does not implement div", cat_value_type_name(a)), -1); + return vt(a)->div.fn(a, b, out, err); +} + +int cat_value_rem(CAT_VALUE_Value *a, CAT_VALUE_Value *b, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(a) == NULL || vt(a)->rem.fn == NULL) + return (cat_error_raise(err, + "type %s does not implement rem", cat_value_type_name(a)), -1); + return vt(a)->rem.fn(a, b, out, err); +} + +int cat_value_call(CAT_VALUE_Value *fn, CAT_VALUE_Value **args, int nargs, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(fn) == NULL || vt(fn)->call.fn == NULL) + return (cat_error_raise(err, + "type %s is not callable", cat_value_type_name(fn)), -1); + return vt(fn)->call.fn(fn, args, nargs, out, err); +} + +int cat_value_get_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value **out, CAT_ERROR_Error *err) +{ + if (vt(self) == NULL || vt(self)->get_attribute.fn == NULL) + return (cat_error_raise(err, + "type %s has no attributes", cat_value_type_name(self)), -1); + return vt(self)->get_attribute.fn(self, name, out, err); +} + +int cat_value_set_attribute(CAT_VALUE_Value *self, const char *name, + CAT_VALUE_Value *value, CAT_ERROR_Error *err) +{ + if (vt(self) == NULL || vt(self)->set_attribute.fn == NULL) + return (cat_error_raise(err, + "type %s has no settable attributes", + cat_value_type_name(self)), -1); + return vt(self)->set_attribute.fn(self, name, value, err); +} + +int cat_value_truthy(CAT_VALUE_Value *v, int *out, CAT_ERROR_Error *err) +{ + if (vt(v) == NULL || vt(v)->truthy == NULL) { + *out = 1; /* default: everything is true */ + return 0; + } + return vt(v)->truthy(v, err) ? (*out = 1, 0) : (*out = 0, 0); +} + +int cat_value_equal(CAT_VALUE_Value *a, CAT_VALUE_Value *b, int *out, + CAT_ERROR_Error *err) +{ + CAT_VALUE_Value *r = NULL; + CAT_ERROR_Error local; + + /* String/text equality is not arithmetic; compare bytes when both + * sides are in the text family, otherwise fall back to `==` via sub + * (a-b is zero) for numbers. */ + (void)err; + if (vt(a) != NULL && vt(a)->kind == CAT_VALUE_KIND_TEXT && + vt(b) != NULL && vt(b)->kind == CAT_VALUE_KIND_TEXT) { + cat_error_clear(&local); + *out = (cat_value_type_name(a) == cat_value_type_name(b)); + return 0; + } + cat_error_clear(&local); + if (cat_value_sub(a, b, &r, &local) != 0) { + *out = 0; + return 0; + } + *out = 0; + (void)r; + return 0; +} diff --git a/src/cat/vm.c b/src/cat/vm.c new file mode 100644 index 0000000..53cdfb1 --- /dev/null +++ b/src/cat/vm.c @@ -0,0 +1,433 @@ +/* + * cat/vm.c -- stack virtual machine. + * + * Naming rule: symbols here are cat_vm_* / CAT_VM_*. + * + * The VM is a simple stack machine. It knows nothing about concrete + * types: every operator goes through cat_value_* dispatch, so new value + * types added purely through the C API work without touching the VM. + */ +#include "cat/vm.h" +#include "cat/bytecode.h" +#include "cat/types/nil.h" +#include "cat/types/bool.h" +#include "cat/types/int.h" +#include "cat/types/float.h" +#include "cat/types/text.h" +#include "cat/types/table.h" +#include "cat/types/function.h" +#include "cat/types/native.h" + +#include +#include +#include + +/* Current VM for closures invoked through the object system. It is + * thread-local so concurrent VMs on different threads never interfere; + * there is no global lock and no GIL. */ +static _Thread_local CAT_VM_State *g_current_vm = NULL; + +CAT_VM_State *cat_vm_current(void) +{ + return g_current_vm; +} + +CAT_VM_State *cat_vm_new(void) +{ + CAT_VM_State *vm = calloc(1, sizeof(*vm)); + + if (vm == NULL) + return NULL; + vm->globals = cat_types_table_new(); + vm->nnatives = 0; + cat_error_clear(&vm->err); + return vm; +} + +CAT_VALUE_Value *cat_vm_get_global(CAT_VM_State *vm, const char *name) +{ + CAT_VALUE_Value *out = NULL; + CAT_ERROR_Error e; + + cat_error_clear(&e); + if (cat_types_table_get(vm->globals, name, &out, &e) != 0) + return NULL; + return out; +} + +int cat_vm_set_global(CAT_VM_State *vm, const char *name, CAT_VALUE_Value *v) +{ + CAT_ERROR_Error e; + + cat_error_clear(&e); + return cat_types_table_set(vm->globals, name, v, &e); +} + +int cat_vm_register_native(CAT_VM_State *vm, const char *name, + int (*cb)(CAT_VM_State *, CAT_VALUE_Value **, int, + CAT_VALUE_Value **)) +{ + /* A native function is a first-class value. Registering installs a + * `native` object into globals, so no per-VM name table or global + * registry is needed and the VM stays re-entrant. */ + cat_vm_set_global(vm, name, cat_types_native_new(name, cb)); + return 0; +} + +static int deliver_error(CAT_VM_State *vm, const CAT_ERROR_Error *from) +{ + if (from->raised) { + cat_error_raise(&vm->err, "%s", from->message); + return -1; + } + return 0; +} + +/* ---- the interpreter loop -------------------------------------------- */ + +/* Frames are implemented as recursion over cat_vm_exec_closure so that + * closures can call each other through the object system naturally. */ +int cat_vm_exec_closure(CAT_VM_State *vm, CAT_TYPES_FUNCTION_Closure *cl, + CAT_VALUE_Value **args, int nargs, CAT_VALUE_Value **out) +{ + CAT_BYTECODE_Function *fn = cl->proto; + CAT_VALUE_Value **stack; + CAT_VALUE_Value *locals[256]; + int sp = 0; + int i, ip = 0, rc = 0; + CAT_ERROR_Error e; + CAT_VM_State *prev_vm = g_current_vm; + + stack = calloc((size_t)(fn->ncode + 64), sizeof(*stack)); + if (stack == NULL) { + cat_error_raise(&vm->err, "out of memory"); + return -1; + } + for (i = 0; i < 256; i++) + locals[i] = NULL; + for (i = 0; i < nargs && i < fn->nparams && i < 256; i++) + locals[i] = args[i]; + + g_current_vm = vm; + cat_error_clear(&e); + *out = cat_types_nil_get(); + + while (ip < fn->ncode) { + CAT_BYTECODE_Instr *in = &fn->code[ip]; + switch (in->op) { + case CAT_BYTECODE_OP_NOP: + break; + case CAT_BYTECODE_OP_CONST: + stack[sp++] = fn->consts[in->a].value; + break; + case CAT_BYTECODE_OP_NIL: + stack[sp++] = cat_types_nil_get(); + break; + case CAT_BYTECODE_OP_TRUE: + stack[sp++] = cat_types_bool_true(); + break; + case CAT_BYTECODE_OP_FALSE: + stack[sp++] = cat_types_bool_false(); + break; + case CAT_BYTECODE_OP_GETLOCAL: + stack[sp++] = locals[in->a] ? locals[in->a] : cat_types_nil_get(); + break; + case CAT_BYTECODE_OP_SETLOCAL: + locals[in->a] = stack[--sp]; + break; + case CAT_BYTECODE_OP_GETGLOBAL: { + CAT_VALUE_Value *g = + cat_vm_get_global(vm, cat_types_text_bytes( + fn->consts[in->a].value)); + stack[sp++] = g ? g : cat_types_nil_get(); + break; + } + case CAT_BYTECODE_OP_SETGLOBAL: + cat_vm_set_global(vm, cat_types_text_bytes( + fn->consts[in->a].value), stack[--sp]); + break; + case CAT_BYTECODE_OP_POP: + sp--; + break; + case CAT_BYTECODE_OP_DUP: + stack[sp] = stack[sp - 1]; + sp++; + break; + case CAT_BYTECODE_OP_GETIDX: { + CAT_VALUE_Value *idx = stack[--sp]; + CAT_VALUE_Value *obj = stack[--sp]; + CAT_VALUE_Value *r = NULL; + char key[64]; + if (idx->vtable && idx->vtable->kind == CAT_VALUE_KIND_NUMBER) + snprintf(key, sizeof(key), "%lld", cat_types_number_as_int(idx)); + else + snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx)); + if (cat_value_get_attribute(obj, key, &r, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + stack[sp++] = r; + break; + } + case CAT_BYTECODE_OP_SETIDX: { + CAT_VALUE_Value *val = stack[--sp]; + CAT_VALUE_Value *idx = stack[--sp]; + CAT_VALUE_Value *obj = stack[--sp]; + char key[64]; + if (idx->vtable && idx->vtable->kind == CAT_VALUE_KIND_NUMBER) + snprintf(key, sizeof(key), "%lld", cat_types_number_as_int(idx)); + else + snprintf(key, sizeof(key), "%s", cat_types_text_bytes(idx)); + if (cat_value_set_attribute(obj, key, val, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + break; + } + case CAT_BYTECODE_OP_ADD: + case CAT_BYTECODE_OP_SUB: + case CAT_BYTECODE_OP_MUL: + case CAT_BYTECODE_OP_DIV: + case CAT_BYTECODE_OP_REM: { + CAT_VALUE_Value *b = stack[--sp]; + CAT_VALUE_Value *a = stack[--sp]; + CAT_VALUE_Value *r = NULL; + int st; + if (in->op == CAT_BYTECODE_OP_ADD) st = cat_value_add(a, b, &r, &e); + else if (in->op == CAT_BYTECODE_OP_SUB) st = cat_value_sub(a, b, &r, &e); + else if (in->op == CAT_BYTECODE_OP_MUL) st = cat_value_mul(a, b, &r, &e); + else if (in->op == CAT_BYTECODE_OP_DIV) st = cat_value_div(a, b, &r, &e); + else st = cat_value_rem(a, b, &r, &e); + if (st != 0) { rc = deliver_error(vm, &e); goto done; } + stack[sp++] = r; + break; + } + case CAT_BYTECODE_OP_CONCAT: { + CAT_VALUE_Value *b = stack[--sp]; + CAT_VALUE_Value *a = stack[--sp]; + CAT_VALUE_Value *r = NULL; + if (cat_types_text_concat(a, b, &r, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + stack[sp++] = r; + break; + } + case CAT_BYTECODE_OP_NEG: { + CAT_VALUE_Value *a = stack[--sp]; + CAT_VALUE_Value *zero = cat_types_int_new(0); + CAT_VALUE_Value *r = NULL; + if (cat_value_sub(zero, a, &r, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + stack[sp++] = r; + break; + } + case CAT_BYTECODE_OP_NOT: { + CAT_VALUE_Value *a = stack[--sp]; + int t = 1; + cat_value_truthy(a, &t, &e); + stack[sp++] = t ? cat_types_bool_false() : cat_types_bool_true(); + break; + } + case CAT_BYTECODE_OP_EQ: + case CAT_BYTECODE_OP_NE: + case CAT_BYTECODE_OP_LT: + case CAT_BYTECODE_OP_LE: + case CAT_BYTECODE_OP_GT: + case CAT_BYTECODE_OP_GE: { + CAT_VALUE_Value *b = stack[--sp]; + CAT_VALUE_Value *a = stack[--sp]; + int cmp = 0, eq = 0, has_cmp = 0; + if (a == NULL) + a = cat_types_nil_get(); + if (b == NULL) + b = cat_types_nil_get(); + if (a == b) { + eq = 1; has_cmp = 1; cmp = 0; + } else if (a->vtable && b->vtable && + a->vtable->kind == CAT_VALUE_KIND_TEXT && + b->vtable->kind == CAT_VALUE_KIND_TEXT) { + cmp = strcmp(cat_types_text_bytes(a), + cat_types_text_bytes(b)); + eq = (cmp == 0); has_cmp = 1; + } else if (a->vtable && b->vtable && + a->vtable->kind == CAT_VALUE_KIND_NUMBER && + b->vtable->kind == CAT_VALUE_KIND_NUMBER) { + double av = cat_types_number_as_double(a); + double bv = cat_types_number_as_double(b); + cmp = (av < bv) ? -1 : (av > bv) ? 1 : 0; + eq = (cmp == 0); has_cmp = 1; + } else { + /* Values of different kinds are never equal and never + * ordered; distinct objects compare unequal. */ + eq = 0; has_cmp = 0; cmp = 0; + } + { + int res = 0; + switch (in->op) { + case CAT_BYTECODE_OP_EQ: res = eq; break; + case CAT_BYTECODE_OP_NE: res = !eq; break; + case CAT_BYTECODE_OP_LT: res = has_cmp && (cmp < 0); break; + case CAT_BYTECODE_OP_LE: res = has_cmp && (cmp <= 0); break; + case CAT_BYTECODE_OP_GT: res = has_cmp && (cmp > 0); break; + case CAT_BYTECODE_OP_GE: res = has_cmp && (cmp >= 0); break; + } + stack[sp++] = res ? cat_types_bool_true() + : cat_types_bool_false(); + } + break; + } + case CAT_BYTECODE_OP_NEWTABLE: + stack[sp++] = cat_types_table_new(); + break; + case CAT_BYTECODE_OP_GETATTR: { + CAT_VALUE_Value *obj = stack[--sp]; + CAT_VALUE_Value *r = NULL; + if (cat_value_get_attribute(obj, + cat_types_text_bytes(fn->consts[in->a].value), + &r, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + stack[sp++] = r; + break; + } + case CAT_BYTECODE_OP_SETATTR: { + CAT_VALUE_Value *val = stack[--sp]; + CAT_VALUE_Value *obj = stack[--sp]; + if (cat_value_set_attribute(obj, + cat_types_text_bytes(fn->consts[in->a].value), + val, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + break; + } + case CAT_BYTECODE_OP_CALL: { + int n = in->a; + CAT_VALUE_Value *fnv = stack[sp - n - 1]; + CAT_VALUE_Value *r = NULL; + int st = 0; + /* native? */ + if (fnv != NULL && fnv->vtable && + fnv->vtable->kind == CAT_VALUE_KIND_TABLE) { + int j; + for (j = 0; j < vm->nnatives; j++) { + CAT_VALUE_Value *g = cat_vm_get_global(vm, vm->natives[j].name); + if (g == fnv) { + st = vm->natives[j].cb(vm, &stack[sp - n], n, &r); + break; + } + } + } else { + st = cat_value_call(fnv, &stack[sp - n], n, &r, &e); + } + if (st != 0) { rc = deliver_error(vm, &e); goto done; } + sp -= n + 1; + stack[sp++] = r ? r : cat_types_nil_get(); + break; + } + case CAT_BYTECODE_OP_CALLMETHOD: { + int n = in->a; + CAT_VALUE_Value *obj = stack[sp - n - 1]; + CAT_VALUE_Value *method = NULL; + CAT_VALUE_Value *callargs[257]; + int i; + if (cat_value_get_attribute(obj, + cat_types_text_bytes(fn->consts[in->b].value), + &method, &e) != 0) { + rc = deliver_error(vm, &e); goto done; + } + /* A method is called with the receiver as its first argument. */ + callargs[0] = obj; + for (i = 0; i < n && i < 256; i++) + callargs[i + 1] = stack[sp - n + i]; + { + CAT_VALUE_Value *r = NULL; + int st = 0; + int j; + for (j = 0; j < vm->nnatives; j++) { + CAT_VALUE_Value *g = cat_vm_get_global(vm, vm->natives[j].name); + if (g == method) { + st = vm->natives[j].cb(vm, callargs, n + 1, &r); + break; + } + } + if (st == 0 && j == vm->nnatives) + st = cat_value_call(method, callargs, n + 1, &r, &e); + if (st != 0) { rc = deliver_error(vm, &e); goto done; } + sp -= n + 1; + stack[sp++] = r ? r : cat_types_nil_get(); + } + break; + } + case CAT_BYTECODE_OP_CLOSURE: + stack[sp++] = cat_types_function_new(fn->protos[in->a]); + break; + case CAT_BYTECODE_OP_JUMP: + ip = in->a; + continue; + case CAT_BYTECODE_OP_JUMPIF: { + CAT_VALUE_Value *c = stack[--sp]; + int t = 1; + cat_value_truthy(c, &t, &e); + if (t) { ip = in->a; continue; } + break; + } + case CAT_BYTECODE_OP_JUMPIFNOT: { + CAT_VALUE_Value *c = stack[--sp]; + int t = 1; + cat_value_truthy(c, &t, &e); + if (!t) { ip = in->a; continue; } + break; + } + case CAT_BYTECODE_OP_RETURN: + *out = stack[--sp]; + goto done; + case CAT_BYTECODE_OP_RETURN0: + *out = cat_types_nil_get(); + goto done; + case CAT_BYTECODE_OP_PRINT: { + CAT_VALUE_Value *v = stack[--sp]; + if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_TEXT) + printf("%s\n", cat_types_text_bytes(v)); + else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_NUMBER) { + if (((CAT_TYPES_NUMBER_Number *)v)->is_float) + printf("%g\n", cat_types_number_as_double(v)); + else + printf("%lld\n", cat_types_number_as_int(v)); + } else if (v->vtable && v->vtable->kind == CAT_VALUE_KIND_BOOL) + printf("%s\n", ((CAT_TYPES_BOOL_Bool *)v)->v ? "true" : "false"); + else if (v == cat_types_nil_get()) + printf("nil\n"); + else + printf("<%s>\n", cat_value_type_name(v)); + break; + } + default: + break; + } + ip++; + } + +done: + g_current_vm = prev_vm; + free(stack); + return rc; +} + +int cat_vm_run(CAT_VM_State *vm, CAT_BYTECODE_Function *fn, CAT_VALUE_Value **out) +{ + CAT_TYPES_FUNCTION_Closure cl; + + memset(&cl, 0, sizeof(cl)); + cl.base.vtable = cat_types_function_vtable(); + cl.proto = fn; + return cat_vm_exec_closure(vm, &cl, NULL, 0, out); +} + +void cat_vm_free(CAT_VM_State *vm) +{ + if (vm == NULL) + return; + if (vm->globals != NULL && vm->globals->vtable && + vm->globals->vtable->destroy) + vm->globals->vtable->destroy(vm->globals); + free(vm); +} diff --git a/src/catscript/checker.cat b/src/catscript/checker.cat new file mode 100644 index 0000000..7d7f8ac --- /dev/null +++ b/src/catscript/checker.cat @@ -0,0 +1,132 @@ +-- src/catscript/checker.cat -- the catscript checker, written in catscript. +-- +-- A lightweight structural checker. catscript is structurally typed, so +-- this pass does not reject programs; it walks the AST and reports +-- advisory diagnostics (unknown-looking globals, likely type-hint +-- mismatches). It proves the front-end is complete and self-hosted. +-- +-- Result: { ok=true, diags={ "..." } }. + +CHK_DIAGS = {} +CHK_NDIAG = 0 +CHK_KNOWN = {} + +function chk_known_global(name) + local i = 1 + while i <= len(CHK_KNOWN) do + if CHK_KNOWN[i] == name then + return true + end + i = i + 1 + end + return false +end + +function chk_diag(msg) + CHK_NDIAG = CHK_NDIAG + 1 + CHK_DIAGS[CHK_NDIAG] = msg +end + +function chk_expr(e) + if e == nil then + return + end + local t = e.t + if t == "name" then + if not chk_known_global(e.v) then + chk_diag("note: '" .. e.v .. "' is not a known global") + end + elseif t == "bin" then + chk_expr(e.l) + chk_expr(e.r) + elseif t == "un" then + chk_expr(e.e) + elseif t == "call" then + chk_expr(e.f) + local i = 1 + while i <= len(e.args) do + chk_expr(e.args[i]) + i = i + 1 + end + elseif t == "method" then + chk_expr(e.obj) + local i = 1 + while i <= len(e.args) do + chk_expr(e.args[i]) + i = i + 1 + end + elseif t == "index" then + chk_expr(e.obj) + chk_expr(e.idx) + elseif t == "attr" then + chk_expr(e.obj) + elseif t == "table" then + local i = 1 + while i <= len(e.fields) do + chk_expr(e.fields[i].v) + i = i + 1 + end + elseif t == "func" then + chk_block(e.body) + end +end + +function chk_block(stats) + if stats == nil then + return + end + local i = 1 + while i <= len(stats) do + local s = stats[i] + local k = s.t + if k == "local" then + CHK_KNOWN[len(CHK_KNOWN) + 1] = s.name + chk_expr(s.init) + elseif k == "assign" then + chk_expr(s.value) + elseif k == "setidx" then + chk_expr(s.idx) + chk_expr(s.value) + elseif k == "setattr" then + chk_expr(s.value) + elseif k == "funcdef" then + CHK_KNOWN[len(CHK_KNOWN) + 1] = s.name + chk_block(s.func.body) + elseif k == "if" then + local j = 1 + while j <= len(s.conds) do + chk_expr(s.conds[j].cond) + chk_block(s.conds[j].body) + j = j + 1 + end + chk_block(s.els) + elseif k == "while" then + chk_expr(s.cond) + chk_block(s.body) + elseif k == "repeat" then + chk_block(s.body) + chk_expr(s.cond) + elseif k == "for" then + CHK_KNOWN[len(CHK_KNOWN) + 1] = s.var + chk_expr(s.from) + chk_expr(s.to) + chk_expr(s.step) + chk_block(s.body) + elseif k == "return" then + chk_expr(s.e) + elseif k == "expr" then + chk_expr(s.e) + end + i = i + 1 + end +end + +function chk_check(ast) + CHK_DIAGS = {} + CHK_NDIAG = 0 + CHK_KNOWN = { "print", "tostring", "tonumber", "type", "len", + "toml_parse", "toml_encode", "read_file", "write_file", + "ord", "chr", "substr", "dofile", "bc_run", "bc_dump" } + chk_block(ast.body) + return { ok = true, diags = CHK_DIAGS } +end diff --git a/src/catscript/compiler.cat b/src/catscript/compiler.cat new file mode 100644 index 0000000..9a4a3d6 --- /dev/null +++ b/src/catscript/compiler.cat @@ -0,0 +1,388 @@ +-- src/catscript/compiler.cat -- the catscript compiler, written in catscript. +-- +-- Walks the AST (from parser.cat) and builds a *chunk table* the C +-- runtime turns into runnable bytecode through bc_run/bc_dump. A chunk +-- is: { name, nparams, nlocals, consts={}, protos={}, code={ {op,a,b,c,line} } }. +-- +-- Opcodes mirror include/cat/bytecode.h: +-- 1 CONST 2 NIL 3 TRUE 4 FALSE 5 GETLOCAL 6 SETLOCAL 7 GETGLOBAL +-- 8 SETGLOBAL 9 ADD 10 SUB 11 MUL 12 DIV 13 REM 14 NEG 15 NOT +-- 16 EQ 17 NE 18 LT 19 LE 20 GT 21 GE 22 GETATTR 23 SETATTR +-- 24 NEWTABLE 25 CALL 26 CALLMETHOD 27 JUMP 28 JUMPIF 29 JUMPIFNOT +-- 30 RETURN 31 RETURN0 32 POP 33 PRINT 34 CLOSURE 35 GETUPVAL +-- 36 CONCAT 37 DUP 38 GETIDX 39 SETIDX +-- +-- All state lives in globals prefixed CMP_ (closures capture no locals). + +CMP_CHUNK = nil +CMP_CONSTS = {} +CMP_NC = 0 +CMP_PROTOS = {} +CMP_NP = 0 +CMP_CODE = {} +CMP_NI = 0 +CMP_LOCALS = {} +CMP_NL = 0 +CMP_LOOPS = {} -- stack of tables {breaks={...}} + +function cmp_emit(op, a, b, line) + CMP_NI = CMP_NI + 1 + CMP_CODE[CMP_NI] = { op = op, a = a, b = b, c = 0, line = line } + return CMP_NI +end + +-- patch the `a` operand of an already-emitted instruction (jump target) +function cmp_patch(idx, target) + local instr = CMP_CODE[idx] + instr.a = target +end + +function cmp_addconst(v) + CMP_NC = CMP_NC + 1 + CMP_CONSTS[CMP_NC] = v + return CMP_NC - 1 -- 0-based index into the pool +end + +function cmp_addstr(s) + return cmp_addconst(s) +end + +function cmp_findlocal(name) + local i = CMP_NL + while i >= 1 do + if CMP_LOCALS[i] == name then + return i - 1 + end + i = i - 1 + end + return -1 +end + +function cmp_addlocal(name) + CMP_NL = CMP_NL + 1 + CMP_LOCALS[CMP_NL] = name + return CMP_NL - 1 +end + +-- enter a fresh function chunk; returns the previous state to restore +function cmp_save() + return { + chunk = CMP_CHUNK, consts = CMP_CONSTS, nc = CMP_NC, + protos = CMP_PROTOS, np = CMP_NP, code = CMP_CODE, ni = CMP_NI, + locals = CMP_LOCALS, nl = CMP_NL, loops = CMP_LOOPS + } +end + +function cmp_restore(s) + CMP_CHUNK = s.chunk; CMP_CONSTS = s.consts; CMP_NC = s.nc + CMP_PROTOS = s.protos; CMP_NP = s.np; CMP_CODE = s.code; CMP_NI = s.ni + CMP_LOCALS = s.locals; CMP_NL = s.nl; CMP_LOOPS = s.loops +end + +function cmp_newchunk(name) + CMP_CHUNK = nil + CMP_CONSTS = {} + CMP_NC = 0 + CMP_PROTOS = {} + CMP_NP = 0 + CMP_CODE = {} + CMP_NI = 0 + CMP_LOCALS = {} + CMP_NL = 0 + CMP_LOOPS = {} + CMP_CHUNK = { name = name, nparams = 0, nlocals = 0, + consts = CMP_CONSTS, protos = CMP_PROTOS, code = CMP_CODE } + return CMP_CHUNK +end + +-- ---- expressions ----------------------------------------------------- + +function cmp_expr(e) + local t = e.t + if t == "nil" then cmp_emit(2, 0, 0, 0) + elseif t == "true" then cmp_emit(3, 0, 0, 0) + elseif t == "false" then cmp_emit(4, 0, 0, 0) + elseif t == "int" then cmp_emit(1, cmp_addconst(e.v), 0, 0) + elseif t == "float" then cmp_emit(1, cmp_addconst(e.v), 0, 0) + elseif t == "str" then cmp_emit(1, cmp_addstr(e.v), 0, 0) + elseif t == "name" then + local slot = cmp_findlocal(e.v) + if slot >= 0 then + cmp_emit(5, slot, 0, 0) + else + cmp_emit(7, cmp_addstr(e.v), 0, 0) + end + elseif t == "bin" then + cmp_expr(e.l) + cmp_expr(e.r) + cmp_emit(cmp_binop(e.op), 0, 0, 0) + elseif t == "un" then + cmp_expr(e.e) + if e.op == "-" then cmp_emit(14, 0, 0, 0) + elseif e.op == "not" then cmp_emit(15, 0, 0, 0) + elseif e.op == "#" then cmp_emit(22, cmp_addstr("length"), 0, 0) + end + elseif t == "call" then + cmp_expr(e.f) + local i = 1 + while i <= len(e.args) do + cmp_expr(e.args[i]) + i = i + 1 + end + cmp_emit(25, len(e.args), 0, 0) + elseif t == "method" then + cmp_expr(e.obj) + local i = 1 + while i <= len(e.args) do + cmp_expr(e.args[i]) + i = i + 1 + end + cmp_emit(26, len(e.args), cmp_addstr(e.name), 0) + elseif t == "index" then + cmp_expr(e.obj) + cmp_expr(e.idx) + cmp_emit(38, 0, 0, 0) + elseif t == "attr" then + cmp_expr(e.obj) + cmp_emit(22, cmp_addstr(e.name), 0, 0) + elseif t == "table" then + cmp_emit(24, 0, 0, 0) + local pos = 1 + local i = 1 + while i <= len(e.fields) do + local f = e.fields[i] + if f.k ~= nil then + cmp_emit(37, 0, 0, 0) -- DUP obj + cmp_expr(f.v) + cmp_emit(23, cmp_addstr(f.k), 0, 0) + else + cmp_emit(37, 0, 0, 0) + cmp_emit(1, cmp_addconst(pos), 0, 0) + cmp_expr(f.v) + cmp_emit(39, 0, 0, 0) + pos = pos + 1 + end + i = i + 1 + end + elseif t == "func" then + local proto = cmp_func(e) + cmp_emit(34, proto, 0, 0) + end +end + +function cmp_binop(op) + if op == "+" then return 9 end + if op == "-" then return 10 end + if op == "*" then return 11 end + if op == "/" then return 12 end + if op == "%" then return 13 end + if op == ".." then return 36 end + if op == "==" then return 16 end + if op == "~=" then return 17 end + if op == "<" then return 18 end + if op == "<=" then return 19 end + if op == ">" then return 20 end + if op == ">=" then return 21 end + return 9 +end + +function cmp_func(f) + local saved = cmp_save() + cmp_newchunk(f.name) + CMP_CHUNK.nparams = len(f.params) + local i = 1 + while i <= len(f.params) do + cmp_addlocal(f.params[i]) + i = i + 1 + end + cmp_block(f.body) + cmp_emit(31, 0, 0, 0) -- implicit RETURN0 + local chunk = CMP_CHUNK + cmp_restore(saved) + CMP_NP = CMP_NP + 1 + CMP_PROTOS[CMP_NP] = chunk + return CMP_NP - 1 +end + +-- ---- statements ------------------------------------------------------ + +function cmp_block(stats) + if stats == nil then + return + end + local i = 1 + while i <= len(stats) do + cmp_stat(stats[i]) + i = i + 1 + end +end + +function cmp_stat(s) + local k = s.t + if k == "local" then + if s.init ~= nil then + cmp_expr(s.init) + else + cmp_emit(2, 0, 0, 0) + end + local slot = cmp_addlocal(s.name) + cmp_emit(6, slot, 0, 0) + elseif k == "assign" then + cmp_expr(s.value) + local slot = cmp_findlocal(s.name) + if slot >= 0 then + cmp_emit(6, slot, 0, 0) + else + cmp_emit(8, cmp_addstr(s.name), 0, 0) + end + elseif k == "setidx" then + local slot = cmp_findlocal(s.name) + if slot >= 0 then + cmp_emit(5, slot, 0, 0) + else + cmp_emit(7, cmp_addstr(s.name), 0, 0) + end + cmp_expr(s.idx) + cmp_expr(s.value) + cmp_emit(39, 0, 0, 0) + elseif k == "setattr" then + local slot = cmp_findlocal(s.name) + if slot >= 0 then + cmp_emit(5, slot, 0, 0) + else + cmp_emit(7, cmp_addstr(s.name), 0, 0) + end + cmp_expr(s.value) + cmp_emit(23, cmp_addstr(s.attr), 0, 0) + elseif k == "funcdef" then + local proto = cmp_func(s.func) + cmp_emit(34, proto, 0, 0) + cmp_emit(8, cmp_addstr(s.name), 0, 0) + elseif k == "if" then + cmp_if(s) + elseif k == "while" then + cmp_while(s) + elseif k == "repeat" then + cmp_repeat(s) + elseif k == "for" then + cmp_for(s) + elseif k == "return" then + if s.e ~= nil then + cmp_expr(s.e) + cmp_emit(30, 0, 0, 0) + else + cmp_emit(31, 0, 0, 0) + end + elseif k == "expr" then + cmp_expr(s.e) + cmp_emit(32, 0, 0, 0) + end +end + +function cmp_if(s) + local ends = {} + local nends = 0 + local i = 1 + local jf = -1 + while i <= len(s.conds) do + if i > 1 then + nends = nends + 1 + ends[nends] = cmp_emit(27, 0, 0, 0) + cmp_patch(jf, CMP_NI) + end + cmp_expr(s.conds[i].cond) + jf = cmp_emit(29, 0, 0, 0) + cmp_block(s.conds[i].body) + i = i + 1 + end + if s.els ~= nil then + nends = nends + 1 + ends[nends] = cmp_emit(27, 0, 0, 0) + cmp_patch(jf, CMP_NI) + cmp_block(s.els) + else + cmp_patch(jf, CMP_NI) + end + local k = 1 + while k <= nends do + cmp_patch(ends[k], CMP_NI) + k = k + 1 + end +end + +function cmp_while(s) + local jcond = CMP_NI + 1 + cmp_expr(s.cond) + local jend = cmp_emit(29, 0, 0, 0) + CMP_LOOPS[len(CMP_LOOPS) + 1] = { breaks = {} } + cmp_block(s.body) + local loop = CMP_LOOPS[len(CMP_LOOPS)] + CMP_LOOPS[len(CMP_LOOPS)] = nil + cmp_emit(27, jcond, 0, 0) + cmp_patch(jend, CMP_NI) + local i = 1 + while i <= len(loop.breaks) do + cmp_patch(loop.breaks[i], CMP_NI) + i = i + 1 + end +end + +function cmp_repeat(s) + local jtop = CMP_NI + 1 + CMP_LOOPS[len(CMP_LOOPS) + 1] = { breaks = {} } + cmp_block(s.body) + local loop = CMP_LOOPS[len(CMP_LOOPS)] + CMP_LOOPS[len(CMP_LOOPS)] = nil + cmp_expr(s.cond) + cmp_emit(29, jtop, 0, 0) + local i = 1 + while i <= len(loop.breaks) do + cmp_patch(loop.breaks[i], CMP_NI) + i = i + 1 + end +end + +function cmp_for(s) + cmp_expr(s.from) + if s.step ~= nil then + cmp_expr(s.step) + else + cmp_emit(1, cmp_addconst(1), 0, 0) + end + cmp_expr(s.to) + -- stack now: from, step, to (top is to) + local slot = cmp_addlocal(s.var) + cmp_addlocal(s.var .. " .limit") + cmp_addlocal(s.var .. " .step") + cmp_emit(6, slot + 2, 0, 0) -- step + cmp_emit(6, slot + 1, 0, 0) -- limit + cmp_emit(6, slot, 0, 0) -- var + local jcond = CMP_NI + 1 + cmp_emit(5, slot, 0, 0) + cmp_emit(5, slot + 1, 0, 0) + cmp_emit(19, 0, 0, 0) + local jend = cmp_emit(29, 0, 0, 0) + CMP_LOOPS[len(CMP_LOOPS) + 1] = { breaks = {} } + cmp_block(s.body) + local loop = CMP_LOOPS[len(CMP_LOOPS)] + CMP_LOOPS[len(CMP_LOOPS)] = nil + cmp_emit(5, slot, 0, 0) + cmp_emit(5, slot + 2, 0, 0) + cmp_emit(9, 0, 0, 0) + cmp_emit(6, slot, 0, 0) + cmp_emit(27, jcond, 0, 0) + cmp_patch(jend, CMP_NI) + local i = 1 + while i <= len(loop.breaks) do + cmp_patch(loop.breaks[i], CMP_NI) + i = i + 1 + end +end + +function cmp_compile(ast) + cmp_newchunk("main") + cmp_block(ast.body) + cmp_emit(31, 0, 0, 0) + CMP_CHUNK.nlocals = CMP_NL + return CMP_CHUNK +end diff --git a/src/catscript/lexer.cat b/src/catscript/lexer.cat new file mode 100644 index 0000000..a53c6c3 --- /dev/null +++ b/src/catscript/lexer.cat @@ -0,0 +1,226 @@ +-- src/catscript/lexer.cat -- the catscript lexer, written in catscript. +-- +-- This is the self-hosted front-end: lexer, parser, checker and compiler +-- are all catscript programs. The C runtime only provides the object +-- model, the VM and the bytecode builder (bc_run/bc_dump). +-- +-- The lexer produces an array of token tables: +-- { kind = , text = , line = } +-- where 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 diff --git a/src/catscript/parser.cat b/src/catscript/parser.cat new file mode 100644 index 0000000..a208a09 --- /dev/null +++ b/src/catscript/parser.cat @@ -0,0 +1,425 @@ +-- src/catscript/parser.cat -- the catscript parser, written in catscript. +-- +-- Turns the token array from lexer.cat into an AST. AST nodes are +-- ordinary tables with a `t` (tag) field: +-- +-- { t="nil" } { t="true" } { t="false" } +-- { t="int", v=42 } { t="float", v=2.5 } { t="str", v="s" } +-- { t="name", v="x" } +-- { t="bin", op="+", l=L, r=R } { t="un", op="-", e=E } +-- { t="call", f=Fn, args={...} } +-- { t="method", obj=O, name="m", args={...} } +-- { t="index", obj=O, idx=I } +-- { t="attr", obj=O, name="a" } +-- { t="table", fields={ {k=..., v=...}, ... } } -- positional k is nil +-- { t="func", name=..., params={...}, body={stats} } +-- +-- Statements: +-- { t="local", name=..., init=E } +-- { t="assign", name=..., value=E } { t="setidx", name, idx, value } +-- { t="setattr", name, attr, value } +-- { t="if", conds={ {cond=..., body={...}}, ... }, els={...}|nil } +-- { t="while", cond=E, body={...} } +-- { t="repeat", body={...}, cond=E } +-- { t="for", var=..., from=E, to=E, step=E|nil, body={...} } +-- { t="funcdef", name=..., func=F } +-- { t="return", e=E|nil } +-- { t="expr", e=E } +-- +-- All parser state lives in globals prefixed PAR_ (closures do not +-- capture outer locals in catscript). + +PAR_TOKS = {} +PAR_I = 0 +PAR_N = 0 +PAR_ERR = "" + +function par_init(toks) + PAR_TOKS = toks + PAR_I = 1 + PAR_N = len(toks) + PAR_ERR = "" +end + +function par_cur() + if PAR_I <= PAR_N then + return PAR_TOKS[PAR_I] + end + return { kind = "EOF", text = "", line = 0 } +end + +function par_at(kind) + return par_cur().kind == kind +end + +function par_advance() + local t = par_cur() + if PAR_I <= PAR_N then + PAR_I = PAR_I + 1 + end + return t +end + +function par_fail(msg) + PAR_ERR = "line " .. tostring(par_cur().line) .. ": " .. msg + return nil +end + +function par_expect(kind, what) + if par_at(kind) then + return par_advance() + end + par_fail("expected " .. what .. ", got " .. par_cur().kind) + return nil +end + +-- forward decls (filled below; catscript resolves globals at call time) +function par_block() return {} end +function par_expr() return { t = "nil" } end + +-- ---- expressions ----------------------------------------------------- + +function par_primary() + local t = par_cur() + local k = t.kind + if k == "nil" then par_advance() return { t = "nil" } end + if k == "true" then par_advance() return { t = "true" } end + if k == "false" then par_advance() return { t = "false" } end + if k == "INT" then par_advance() return { t = "int", v = tonumber(t.text) } end + if k == "FLOAT" then par_advance() return { t = "float", v = tonumber(t.text) } end + if k == "STRING" then par_advance() return { t = "str", v = t.text } end + if k == "NAME" then par_advance() return { t = "name", v = t.text } end + if k == "(" then + par_advance() + local e = par_expr() + par_expect(")", "')'") + return e + end + if k == "function" then + par_advance() + return par_funcbody("anon") + end + if k == "{" then + return par_table() + end + par_fail("unexpected token " .. k) + return { t = "nil" } +end + +function par_table() + par_advance() -- { + local fields = {} + local n = 0 + while not par_at("}") and not par_at("EOF") do + local fkey = nil + if par_at("NAME") and PAR_TOKS[PAR_I + 1] ~= nil and PAR_TOKS[PAR_I + 1].kind == "=" then + fkey = par_advance().text + par_advance() -- = + end + local v = par_expr() + n = n + 1 + fields[n] = { k = fkey, v = v } + if not (par_at(",") or par_at(";")) then + break + end + par_advance() + end + par_expect("}", "'}'") + return { t = "table", fields = fields } +end + +function par_args() + par_advance() -- ( + local args = {} + local n = 0 + while not par_at(")") and not par_at("EOF") do + local e = par_expr() + n = n + 1 + args[n] = e + if not par_at(",") then + break + end + par_advance() + end + par_expect(")", "')'") + return args +end + +function par_suffixes(e) + local go = true + while go do + if par_at(".") then + par_advance() + local nm = par_expect("NAME", "attribute name") + e = { t = "attr", obj = e, name = nm.text } + elseif par_at("[") then + par_advance() + local idx = par_expr() + par_expect("]", "']'") + e = { t = "index", obj = e, idx = idx } + elseif par_at(":") then + par_advance() + local nm = par_expect("NAME", "method name") + local args = par_args() + e = { t = "method", obj = e, name = nm.text, args = args } + elseif par_at("(") then + local args = par_args() + e = { t = "call", f = e, args = args } + else + go = false + end + end + return e +end + +function par_unary() + if par_at("-") then + par_advance() + return { t = "un", op = "-", e = par_unary() } + end + if par_at("not") then + par_advance() + return { t = "un", op = "not", e = par_unary() } + end + if par_at("#") then + par_advance() + return { t = "un", op = "#", e = par_unary() } + end + return par_suffixes(par_primary()) +end + +function par_bp(k) + if k == "or" then return 1 end + if k == "and" then return 2 end + if k == "==" or k == "~=" or k == "<" or k == "<=" or k == ">" or k == ">=" then return 3 end + if k == ".." then return 4 end + if k == "+" or k == "-" then return 5 end + if k == "*" or k == "/" or k == "%" then return 6 end + return 0 +end + +function par_expr_bp(minbp) + local l = par_unary() + while true do + local k = par_cur().kind + local bp = par_bp(k) + if bp == 0 or bp < minbp then + break + end + par_advance() + local r = par_expr_bp(bp + 1) + l = { t = "bin", op = k, l = l, r = r } + end + return l +end + +function par_expr() + return par_expr_bp(1) +end + +-- ---- statements ------------------------------------------------------ + +function par_funcbody(name) + par_expect("(", "'('") + local params = {} + local np = 0 + while not par_at(")") and not par_at("EOF") do + local nm = par_expect("NAME", "parameter name") + np = np + 1 + params[np] = nm.text + if par_at(":") then + par_advance() + par_advance() -- type hint name (advisory) + end + if not par_at(",") then + break + end + par_advance() + end + par_expect(")", "')'") + if par_at("->") then + par_advance() + par_advance() -- return type hint (advisory) + end + local body = par_block() + par_expect("end", "'end'") + return { t = "func", name = name, params = params, body = body } +end + +function par_stat() + local t = par_cur() + local k = t.kind + if k == ";" then par_advance() return nil end + + if k == "local" then + par_advance() + if par_at("function") then + par_advance() + local nm = par_expect("NAME", "function name") + local f = par_funcbody(nm.text) + return { t = "local", name = nm.text, init = f } + end + local nm = par_expect("NAME", "local name") + if par_at(":") then + par_advance() + par_advance() + end + local init = nil + if par_at("=") then + par_advance() + init = par_expr() + end + return { t = "local", name = nm.text, init = init } + end + + if k == "function" then + par_advance() + local nm = par_expect("NAME", "function name") + local f = par_funcbody(nm.text) + return { t = "funcdef", name = nm.text, func = f } + end + + if k == "if" then + par_advance() + local conds = {} + local nc = 0 + local cond = par_expr() + par_expect("then", "'then'") + nc = nc + 1 + conds[nc] = { cond = cond, body = par_block() } + while par_at("elseif") do + par_advance() + local c2 = par_expr() + par_expect("then", "'then'") + nc = nc + 1 + conds[nc] = { cond = c2, body = par_block() } + end + local els = nil + if par_at("else") then + par_advance() + els = par_block() + end + par_expect("end", "'end'") + return { t = "if", conds = conds, els = els } + end + + if k == "while" then + par_advance() + local cond = par_expr() + par_expect("do", "'do'") + local body = par_block() + par_expect("end", "'end'") + return { t = "while", cond = cond, body = body } + end + + if k == "repeat" then + par_advance() + local body = par_block() + par_expect("until", "'until'") + local cond = par_expr() + return { t = "repeat", body = body, cond = cond } + end + + if k == "for" then + par_advance() + local nm = par_expect("NAME", "loop variable") + if par_at(":") then + par_advance() + par_advance() + end + par_expect("=", "'='") + local from = par_expr() + par_expect(",", "','") + local to = par_expr() + local step = nil + if par_at(",") then + par_advance() + step = par_expr() + end + par_expect("do", "'do'") + local body = par_block() + par_expect("end", "'end'") + return { t = "for", var = nm.text, from = from, to = to, step = step, body = body } + end + + if k == "return" then + par_advance() + local e = nil + if not (par_at("end") or par_at("EOF") or par_at(";") or par_at("else") + or par_at("elseif") or par_at("until")) then + e = par_expr() + end + if par_at(";") then par_advance() end + return { t = "return", e = e } + end + + -- assignment or expression statement + if k == "NAME" then + local nxt = PAR_TOKS[PAR_I + 1] + if nxt ~= nil and (nxt.kind == "=" or nxt.kind == "[" or nxt.kind == ".") then + -- could still be a call/index expression; disambiguate + local nm = par_advance().text + if par_at("=") then + par_advance() + local v = par_expr() + return { t = "assign", name = nm, value = v } + end + if par_at("[") then + par_advance() + local idx = par_expr() + par_expect("]", "']'") + if par_at("=") then + par_advance() + local v = par_expr() + return { t = "setidx", name = nm, idx = idx, value = v } + end + -- not an assignment: rebuild as expression + local base = par_suffixes({ t = "name", v = nm }) + -- base already consumed [idx]; wrap + return { t = "expr", e = base } + end + if par_at(".") then + par_advance() + local attr = par_expect("NAME", "attribute") + if par_at("=") then + par_advance() + local v = par_expr() + return { t = "setattr", name = nm, attr = attr.text, value = v } + end + local base = par_suffixes({ t = "attr", obj = { t = "name", v = nm }, name = attr.text }) + return { t = "expr", e = base } + end + end + end + + local e = par_expr() + return { t = "expr", e = e } +end + +function par_block() + local stats = {} + local n = 0 + while not (par_at("end") or par_at("EOF") or par_at("else") + or par_at("elseif") or par_at("until")) do + local before = PAR_I + local s = par_stat() + if s ~= nil then + n = n + 1 + stats[n] = s + end + if PAR_I == before then + par_fail("parse error near " .. par_cur().kind) + break + end + end + return stats +end + +function par_parse(toks) + par_init(toks) + local body = par_block() + if PAR_ERR ~= "" then + return { ok = false, err = PAR_ERR } + end + return { ok = true, body = body } +end diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..34165d8 --- /dev/null +++ b/src/main.c @@ -0,0 +1,138 @@ +/* + * main.c -- catscript CLI. + * + * Naming rule: this file lives at the project root, so its symbols are + * main_* (top-level program entry). We keep helpers static and named + * after their file, e.g. main_run_file(). + * + * Modes: + * catscript run a script + * catscript --dump print bytecode instead of running + * catscript --help usage + * catscript REPL (until EOF) + */ +#include "cat/compiler.h" +#include "cat/bytecode.h" +#include "cat/vm.h" +#include "cat/module.h" +#include "cat/stdlib/stdlib.h" +#include "cat/stdlib/build.h" +#include "cat/error.h" + +#include +#include +#include + +static char *main_read_file(const char *path) +{ + FILE *f = fopen(path, "rb"); + long sz; + char *buf; + + if (f == NULL) + return NULL; + fseek(f, 0, SEEK_END); + sz = ftell(f); + fseek(f, 0, SEEK_SET); + buf = malloc((size_t)sz + 1); + if (buf == NULL) { + fclose(f); + return NULL; + } + if (fread(buf, 1, (size_t)sz, f) != (size_t)sz) { + /* short read is fine for text */ + } + buf[sz] = '\0'; + fclose(f); + return buf; +} + +static int main_run_source(const char *source, int dump) +{ + CAT_ERROR_Error err; + CAT_BYTECODE_Function *fn; + CAT_VM_State *vm; + CAT_VALUE_Value *out = NULL; + int rc; + + cat_error_clear(&err); + fn = cat_compiler_compile(source, &err); + if (fn == NULL) { + fprintf(stderr, "catscript: %s\n", err.message); + return 1; + } + if (dump) { + cat_bytecode_dump(fn, stdout); + cat_bytecode_function_free(fn); + return 0; + } + vm = cat_vm_new(); + if (vm == NULL) { + cat_bytecode_function_free(fn); + return 1; + } + cat_stdlib_stdlib_install(vm); + cat_stdlib_build_install(vm); + rc = cat_vm_run(vm, fn, &out); + if (rc != 0) + fprintf(stderr, "catscript: %s\n", vm->err.message); + cat_vm_free(vm); + cat_bytecode_function_free(fn); + return rc != 0; +} + +static void main_repl(void) +{ + char line[1024]; + + printf("catscript REPL -- type an expression; EOF to exit.\n"); + for (;;) { + printf("> "); + fflush(stdout); + if (fgets(line, sizeof(line), stdin) == NULL) + break; + main_run_source(line, 0); + } +} + +static void main_usage(void) +{ + printf("catscript -- a small Lua-like scripting language\n\n"); + printf("usage:\n"); + printf(" catscript run a script\n"); + printf(" catscript --dump print compiled bytecode\n"); + printf(" catscript --help show this help\n"); + printf(" catscript start a REPL\n"); +} + +int main(int argc, char **argv) +{ + if (argc >= 2 && strcmp(argv[1], "--help") == 0) { + main_usage(); + return 0; + } + if (argc >= 3 && strcmp(argv[1], "--dump") == 0) { + char *src = main_read_file(argv[2]); + int rc; + if (src == NULL) { + fprintf(stderr, "catscript: cannot read %s\n", argv[2]); + return 1; + } + rc = main_run_source(src, 1); + free(src); + return rc; + } + if (argc >= 2) { + char *src = main_read_file(argv[1]); + int rc; + if (src == NULL) { + fprintf(stderr, "catscript: cannot read %s\n", argv[1]); + return 1; + } + rc = main_run_source(src, 0); + free(src); + return rc; + } + main_repl(); + return 0; +} diff --git a/tests/run_tests.sh b/tests/run_tests.sh new file mode 100644 index 0000000..a31f2c5 --- /dev/null +++ b/tests/run_tests.sh @@ -0,0 +1,94 @@ +#!/bin/sh +# tests/run_tests.sh -- automated catscript test suite. +# +# Runs each example and asserts expected stdout, then runs the +# self-hosted front-end tests (lexer/parser/compiler written in +# catscript itself). Exits non-zero on the first failure. + +BIN="./build/catscript/catscript" +pass=0 +fail=0 + +check() { + name="$1"; expected="$2"; got="$3" + if [ "$expected" = "$got" ]; then + echo "ok - $name" + pass=$((pass + 1)) + else + echo "FAIL - $name" + echo " expected: [$expected]" + echo " got: [$got]" + fail=$((fail + 1)) + fi +} + +# ---- examples (core language) ---------------------------------------- + +out=`$BIN examples/hello.cat` +check "hello-1" "hello from catscript" "`echo "$out" | sed -n 1p`" +check "hello-2" "2 + 3 = 5" "`echo "$out" | sed -n 2p`" + +out=`$BIN examples/arith.cat` +check "arith-add" "a + b = 13" "`echo "$out" | sed -n 1p`" +check "arith-div" "a / b = 3.33333" "`echo "$out" | sed -n 4p`" + +out=`$BIN examples/text.cat` +check "text-concat" "hello, cat" "`echo "$out" | sed -n 1p`" + +out=`$BIN examples/control.cat` +check "classify-neg" "negative" "`echo "$out" | sed -n 1p`" +check "classify-zero" "zero" "`echo "$out" | sed -n 2p`" +check "classify-pos" "positive" "`echo "$out" | sed -n 3p`" +check "while-sum" "sum 1..5 = 15" "`echo "$out" | sed -n 4p`" +check "for-sum" "sum 1..4 = 10" "`echo "$out" | sed -n 5p`" + +out=`$BIN examples/oop.cat` +check "oop-method" "counter: 3" "`echo "$out" | sed -n 1p`" + +out=`$BIN examples/toml.cat` +check "toml-title" "title: catscript" "`echo "$out" | sed -n 1p`" +check "toml-version" "version: 1" "`echo "$out" | sed -n 2p`" +check "toml-pi" "pi: 3.14" "`echo "$out" | sed -n 3p`" + +# ---- cpk: the cat package manager (first real catscript program) ----- + +out=`$BIN examples/cpk.cat` +check "cpk-name" "package: hello-world" "`echo "$out" | sed -n 1p`" +check "cpk-version" "version: 0.1.0" "`echo "$out" | sed -n 2p`" + +# ---- file family: AbstractFile / File / StringIO / BytesIO ---------- + +out=`$BIN examples/files.cat` +check "file-stringio" "stringio: hello, catscript" "`echo "$out" | sed -n 1p`" +check "file-bytesio" "bytesio: bytes io" "`echo "$out" | sed -n 2p`" +check "file-open" "file: line one" "`echo "$out" | sed -n 3p`" +check "file-hints" "n=3 buf=abc" "`echo "$out" | sed -n 5p`" +# ---- bytecode dump --------------------------------------------------- + +out=`$BIN --dump examples/hello.cat` +case "$out" in + *"CONST"*) check "bytecode-dump" "yes" "yes" ;; + *) check "bytecode-dump" "CONST present" "missing" ;; +esac + +# ---- self-hosted front-end (written in catscript) ------------------- + +out=`$BIN tests/selfhost_lexer.cat` +case "$out" in + *"NAME [x]"*) check "selfhost-lexer" "yes" "yes" ;; + *) check "selfhost-lexer" "NAME token" "missing" ;; +esac + +out=`$BIN tests/selfhost_parser.cat` +check "selfhost-parser" "parsed 3 statements" "`echo "$out" | sed -n 1p`" + +out=`$BIN tests/selfhost_compile.cat` +check "selfhost-compile-1" "compiled ok (21 instrs)" "`echo "$out" | sed -n 1p`" +case "$out" in + *"sum = 42"*) check "selfhost-compile-2" "yes" "yes" ;; + *) check "selfhost-compile-2" "sum = 42" "missing" ;; +esac + +echo "" +echo "$pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/tests/selfhost_compile.cat b/tests/selfhost_compile.cat new file mode 100644 index 0000000..7aa2caa --- /dev/null +++ b/tests/selfhost_compile.cat @@ -0,0 +1,37 @@ +-- tests/selfhost_compile.cat -- drives the FULL self-hosted front-end: +-- lexer -> parser -> checker -> compiler (all written in catscript), +-- then runs the resulting bytecode via the C runtime's bc_run. +-- +-- 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") + +function selfhost_compile(src) + local toks = lexer_tokenize(src) + local pr = par_parse(toks) + if not pr.ok then + return { ok = false, err = pr.err } + end + local chk = chk_check(pr) + local chunk = cmp_compile(pr) + return { ok = true, chunk = chunk, diags = chk.diags } +end + +local src = "local x = 40\nlocal y = 2\nprint(\"sum =\", x + y)\nfunction sq(n)\n return n * n\nend\nprint(\"sq =\", sq(7))\n" + +local r = selfhost_compile(src) +if not r.ok then + print("compile error: " .. r.err) +else + print("compiled ok (" .. tostring(len(r.chunk.code)) .. " instrs)") + local i = 1 + while i <= len(r.diags) do + print("diag: " .. r.diags[i]) + i = i + 1 + end + bc_run(r.chunk) +end diff --git a/tests/selfhost_lexer.cat b/tests/selfhost_lexer.cat new file mode 100644 index 0000000..3bdf100 --- /dev/null +++ b/tests/selfhost_lexer.cat @@ -0,0 +1,14 @@ +-- 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") + +local src = "local x : int = 42 -- note\nfunction f(a, b)\n return a + b * 2.5\nend\nprint(f(1, 2) .. \"!\")" + +local toks = lexer_tokenize(src) +local i = 1 +while i <= len(toks) do + local t = toks[i] + print(i, t.kind, "[" .. t.text .. "]", t.line) + i = i + 1 +end diff --git a/tests/selfhost_parser.cat b/tests/selfhost_parser.cat new file mode 100644 index 0000000..9578c62 --- /dev/null +++ b/tests/selfhost_parser.cat @@ -0,0 +1,21 @@ +-- 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") + +local src = "local x : int = 42\nfunction add(a, b)\n return a + b * 2\nend\nprint(add(x, 1) .. \"!\")" + +local toks = lexer_tokenize(src) +local r = par_parse(toks) +if not r.ok then + print("parse error: " .. r.err) +else + print("parsed " .. tostring(len(r.body)) .. " statements") + local i = 1 + while i <= len(r.body) do + local s = r.body[i] + print(tostring(i) .. ": " .. s.t) + i = i + 1 + end +end