From 95d7e3f80007a48af042d2fbcce1d7278fcf0677 Mon Sep 17 00:00:00 2001 From: Marcel Guinhos Date: Tue, 20 Oct 2026 21:12:51 +0000 Subject: [PATCH] catblocks: linguagem visual com plugins wasm --- .gitignore | 4 + Makefile | 78 +++ README.md | 134 +++++ apps/android/AndroidManifest.xml | 23 + apps/android/cpp/main.c | 39 ++ apps/android/res/values/strings.xml | 1 + docs/ANDROID.md | 21 + docs/LIMITACOES.md | 10 + include/catblocks/ir.h | 66 +++ include/catblocks/plugin.h | 49 ++ include/catblocks/programs.h | 6 + include/catblocks/wasm.h | 41 ++ projects/editor.catblocks | 20 + scripts/blockflags.sh | 17 + scripts/build_android.sh | 68 +++ src/catblocks/interp.c | 26 + src/catblocks/ir.c | 261 +++++++++ src/catblocks/plugin.c | 93 +++ .../plugins/backends/opengl/backend.c | 10 + .../plugins/backends/vulkan/backend.c | 19 + src/catblocks/plugins/blocks/block_template.c | 66 +++ src/catblocks/plugins/compilers/c_plugin.c | 34 ++ .../plugins/compilers/plugin_common.h | 52 ++ src/catblocks/plugins/compilers/plugin_emit.h | 92 +++ src/catblocks/plugins/compilers/wasm_plugin.c | 113 ++++ src/catblocks/plugins/compilers/wat_plugin.c | 34 ++ src/catblocks/programs.c | 22 + src/catblocks/wasm.c | 545 ++++++++++++++++++ src/main.c | 116 ++++ tests/blocks_test.c | 35 ++ tests/ir_test.c | 32 + tests/plugins_test.c | 64 ++ tests/run.sh | 46 ++ tests/wasm_demo.c | 13 + tests/wasm_smoke.c | 44 ++ 35 files changed, 2294 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 apps/android/AndroidManifest.xml create mode 100644 apps/android/cpp/main.c create mode 100644 apps/android/res/values/strings.xml create mode 100644 docs/ANDROID.md create mode 100644 docs/LIMITACOES.md create mode 100644 include/catblocks/ir.h create mode 100644 include/catblocks/plugin.h create mode 100644 include/catblocks/programs.h create mode 100644 include/catblocks/wasm.h create mode 100644 projects/editor.catblocks create mode 100755 scripts/blockflags.sh create mode 100755 scripts/build_android.sh create mode 100644 src/catblocks/interp.c create mode 100644 src/catblocks/ir.c create mode 100644 src/catblocks/plugin.c create mode 100644 src/catblocks/plugins/backends/opengl/backend.c create mode 100644 src/catblocks/plugins/backends/vulkan/backend.c create mode 100644 src/catblocks/plugins/blocks/block_template.c create mode 100644 src/catblocks/plugins/compilers/c_plugin.c create mode 100644 src/catblocks/plugins/compilers/plugin_common.h create mode 100644 src/catblocks/plugins/compilers/plugin_emit.h create mode 100644 src/catblocks/plugins/compilers/wasm_plugin.c create mode 100644 src/catblocks/plugins/compilers/wat_plugin.c create mode 100644 src/catblocks/programs.c create mode 100644 src/catblocks/wasm.c create mode 100644 src/main.c create mode 100644 tests/blocks_test.c create mode 100644 tests/ir_test.c create mode 100644 tests/plugins_test.c create mode 100755 tests/run.sh create mode 100644 tests/wasm_demo.c create mode 100644 tests/wasm_smoke.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed68279 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/ +*.o +*.wasm +!src/**/*.wasm diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f15de42 --- /dev/null +++ b/Makefile @@ -0,0 +1,78 @@ +# catblocks - Makefile +# Saida: build///bin/catblocks[.formato]; Android: build/android//apk/catblocks.apk +SHELL := /bin/sh + +OS := $(shell uname -s | tr 'A-Z' 'a-z') +ARCH := $(shell uname -m) +BIN := build/$(OS)/$(ARCH)/bin +PLG := build/plugins + +CC ?= gcc +CFLAGS ?= -std=c11 -O2 -Wall -Iinclude +SRC = src/catblocks/wasm.c src/catblocks/plugin.c src/catblocks/ir.c \ + src/catblocks/interp.c src/catblocks/programs.c src/main.c + +# NDK / clang wasm32 +NDK ?= /home/ovelha/android-sdk/ndk/android-ndk-r26d +WASMCLANG ?= $(NDK)/toolchains/llvm/prebuilt/linux-x86_64/bin/clang +WASMFLAGS = --target=wasm32 -nostdlib -O0 -Wl,--no-entry -Wl,--export-all +export PATH := /home/ovelha/wasmbin:$(PATH) + +all: $(BIN)/catblocks plugins backends + +$(BIN)/catblocks: $(SRC) include/catblocks/*.h + @mkdir -p $(BIN) + $(CC) $(CFLAGS) $(SRC) -o $@ + @echo "== built $@ ==" + +# ---- plugins compiladores (IR->wat/c/wasm) ---- +COMPILERS = compiler_wat compiler_c compiler_wasm +plugins: $(PLG)/compiler_wat.wasm $(PLG)/compiler_c.wasm $(PLG)/compiler_wasm.wasm blocks + +$(PLG)/compiler_wat.wasm: src/catblocks/plugins/compilers/wat_plugin.c + @mkdir -p $(PLG) + $(WASMCLANG) $(WASMFLAGS) -o $@ $< +$(PLG)/compiler_c.wasm: src/catblocks/plugins/compilers/c_plugin.c + @mkdir -p $(PLG) + $(WASMCLANG) $(WASMFLAGS) -o $@ $< +$(PLG)/compiler_wasm.wasm: src/catblocks/plugins/compilers/wasm_plugin.c + @mkdir -p $(PLG) + $(WASMCLANG) $(WASMFLAGS) -o $@ $< + +# ---- blocos estilo Scratch (.wasm) ---- +BT = src/catblocks/plugins/blocks/block_template.c +BFLAGS = $(WASMFLAGS) +blocks: $(PLG)/blocks/add.wasm $(PLG)/blocks/subtract.wasm $(PLG)/blocks/multiply.wasm \ + $(PLG)/blocks/divide.wasm $(PLG)/blocks/and.wasm $(PLG)/blocks/or.wasm \ + $(PLG)/blocks/not.wasm $(PLG)/blocks/if.wasm $(PLG)/blocks/else.wasm \ + $(PLG)/blocks/while.wasm $(PLG)/blocks/for.wasm $(PLG)/blocks/when_start.wasm + +$(PLG)/blocks/%.wasm: $(BT) + @mkdir -p $(PLG)/blocks + $(WASMCLANG) $(BFLAGS) -o $@ $(shell ./scripts/blockflags.sh $* ) $< + +test: all + ./tests/run.sh + +# ---- backends graficos (plugins .wasm; desktop) ---- +backends: $(PLG)/backends/vulkan.wasm $(PLG)/backends/opengl.wasm + +$(PLG)/backends/vulkan.wasm: src/catblocks/plugins/backends/vulkan/backend.c + @mkdir -p $(PLG)/backends + $(WASMCLANG) $(WASMFLAGS) -o $@ $< +$(PLG)/backends/opengl.wasm: src/catblocks/plugins/backends/opengl/backend.c + @mkdir -p $(PLG)/backends + $(WASMCLANG) $(WASMFLAGS) -o $@ $< + +# ---- Android: reaproveita o pipeline C-only validado (android-hello) ---- +# Requer /home/ovelha/android-hello (build.sh + sign.sh). Ver docs/ANDROID.md. +APK = build/android/arm64-v8a/apk/catblocks.apk +android: + @echo "catblocks Android: pipeline reaproveitado de /home/ovelha/android-hello" + @mkdir -p $(dir $(APK)) + @sh scripts/build_android.sh + +clean: + rm -rf build/plugins $(BIN) + +.PHONY: all plugins blocks backends test clean android diff --git a/README.md b/README.md new file mode 100644 index 0000000..ea013de --- /dev/null +++ b/README.md @@ -0,0 +1,134 @@ +# catblocks + +Linguagem de programação visual **baseada em nós**, onde **tudo é um plugin `.wasm`**: +os blocos, os compiladores (IR → `.wat` / `.c` / `.wasm`) e os backends gráficos. +Inclui um **interpretador de WebAssembly** próprio (host-side, sem JIT), um **IR de +grafo de nós** com interpretador, e um pipeline de compilação provado ponta-a-ponta. + +Estado: **núcleo funciona de verdade** (ver "O que funciona"). O editor visual +auto-hospedado e os backends gráficos estão **esboçados** (não há GPU/display neste host). + +## Construir + +```sh +make # compila o binário + todos os plugins .wasm (compiladores, blocos, backends) +make test # prova ponta-a-ponta (ver tests/run.sh) +make android # gera o APK (reaproveita o pipeline C-only do android-hello) +``` + +Requer: `gcc`, `make`, e o clang wasm32 do NDK. Para o wasm-ld, o symlink +`/home/ovelha/wasmbin/wasm-ld` é usado (o Makefile adiciona-o ao `PATH`). + +## Árvore + +``` +include/catblocks/wasm.h contrato do interpretador WASM +include/catblocks/ir.h IR (grafo de nós) + emissores +include/catblocks/plugin.h ABI dos plugins .wasm (compiladores e blocos) +include/catblocks/programs.h programas de exemplo +src/catblocks/wasm.c interpretador WebAssembly (MVP + sign-ext) +src/catblocks/ir.c grafo de nós, avaliador, emissores wat/c, serialização CBIR +src/catblocks/interp.c interpretador de IR (com captura de saída) +src/catblocks/programs.c programa de exemplo (soma 1..n) +src/catblocks/plugin.c carregador/executor de plugins .wasm +src/catblocks/plugins/compilers/{wat,c,wasm}_plugin.c IR->wat / IR->c / IR->wasm +src/catblocks/plugins/compilers/plugin_common.h parser CBIR (freestanding) +src/catblocks/plugins/compilers/plugin_emit.h emissores partilhados +src/catblocks/plugins/blocks/block_template.c template dos blocos Scratch +src/catblocks/plugins/backends/{vulkan,opengl}/backend.c esboço dos backends +src/main.c CLI +apps/android/ NativeActivity (manifest/res/main.c) +projects/editor.catblocks projeto do editor auto-hospedado (grafo de exemplo) +scripts/blockflags.sh flags por bloco +scripts/build_android.sh pipeline APK (clang NDK + aapt2 + zipalign + sign.sh) +tests/ provas executáveis +Makefile +``` + +## ABI dos plugins `.wasm` + +Todo plugin é um módulo wasm32 sem libc que exporta: + +| export | significado | +|---|---| +| `cb_abi() -> i32` | versão da ABI (deve ser 1) | +| `cb_in_addr() -> i32` | endereço do buffer de entrada (CBIR) | +| `cb_out_addr() -> i32` | endereço do buffer de saída | +| `cb_run(in_len) -> i32` | corre o plugin; devolve bytes escritos na saída | + +Blocos (estilo Scratch) exportam também: + +| export | interface | +|---|---| +| `on_plug(self, other) -> i32` | `BlockLike` (aceita encaixe) | +| `on_unplug(self, other) -> i32` | `BlockLike` (aceita desencaixe) | +| `on_render(self) -> i32` | `Renderable` (primitiva: `rect x y w h cor`) | +| `block_name/block_color/block_cat` | metadados visuais | + +O host descobre as interfaces com `cb_plugin_has_blocklike()` / `cb_plugin_has_renderable()` +(presentes se os exports existirem). + +## CLI + +```sh +build/linux/x86_64/bin/catblocks run # interpreta o grafo +build/linux/x86_64/bin/catblocks ir # imprime o CBIR serializado +build/linux/x86_64/bin/catblocks wat # IR->.wat (plugin .wasm) -> build/catblocks_out.wat +build/linux/x86_64/bin/catblocks c # IR->.c (plugin .wasm) -> build/catblocks_out.c +build/linux/x86_64/bin/catblocks wasm # IR->.wasm (plugin .wasm) -> build/catblocks_out.wasm +build/linux/x86_64/bin/catblocks blocks # lista os blocos .wasm e interfaces +``` + +## Saídas + +``` +build/linux/x86_64/bin/catblocks binário +build/plugins/compiler_{wat,c,wasm}.wasm compiladores (plugins .wasm) +build/plugins/blocks/*.wasm blocos estilo Scratch +build/plugins/backends/{vulkan,opengl}.wasm backends (esboço) +build/android/arm64-v8a/apk/catblocks.apk APK (assinado v1) +``` + +## O que funciona (com evidência) + +- **Interpretador WebAssembly próprio** (`src/catblocks/wasm.c`): carrega `.wasm` + MVP e corre `add`, `sum_to` (while), `fact` (recursão), `fib` — todos batem com + os valores esperados. Suporta i32/i64, locais/globais, load/store **com offset**, + `call` (incl. imports de host), `block/loop/if/else/br/br_if/br_table/return/end`, + `select`, `drop`. +- **IR de grafo de nós** com interpretador: o programa de exemplo (soma 1..100 com + `for`) devolve **5050**. +- **Compiladores como plugins `.wasm`** (três módulos wasm32 reais, carregados pelo + host): IR→`.wat`, IR→`.c`, IR→`.wasm`. + - O `.c` gerado compila com **gcc** e imprime **5050**. + - O `.wasm` gerado é carregado pelo interpretador próprio e corre com o + `print` do host, imprimindo **5050**. +- **Blocos `.wasm` estilo Scratch** (12 módulos): aritmética, lógica, controlo; + todos assinam `BlockLike`; os que desenham assinam `Renderable`; cores por + categoria (`0x4C97FF` aritmética, `0x59C059` lógica, `0xFFAB19` controlo, + `0xFFBF00` eventos). +- **APK Android** `build/android/arm64-v8a/apk/catblocks.apk` construído sem Java + (clang NDK + aapt2 + zipalign) e **assinado v1** (verificação `openssl`: + "Verification successful"). O `.so` contém o núcleo catblocks. +- **`tests/run.sh`** executa as 6 provas e termina com `== TUDO OK ==`. + +## O que está esboçado / o que falta + +- **Editor visual auto-hospedado**: existe o projeto `projects/editor.catblocks` + (um grafo catblocks) e os backends como módulos, mas **não há UI a correr**. +- **Backends Vulkan/OpenGL**: a ABI está definida e os módulos compilam como + plugins `.wasm` (stubs). A implementação Vulkan+GLFW real **não foi escrita**. + **Este host é headless**: não há `DISPLAY` nem `vulkaninfo`; existem ICDs + (`/usr/share/vulkan/icd.d/`, incl. `lvp_icd.json` = lavapipe software), mas não + foram exercitados. Numa máquina com GPU/display, o backend deve implementar: + instance/surface/swapchain/renderpass/pipeline/command buffers (reaproveitar + `/home/ovelha/android-vulkan`) e, no Android, `android_native_app_glue`. +- **Blocos**: metadados e interfaces funcionam; a *avaliação* por bloco é + demonstrativa (`cb_run` devolve identidade), não uma semântica completa de blocos. +- **Editor na própria linguagem**: só o esqueleto do grafo. +- Sem validador wasm completo, sem tables/`call_indirect`, sem SIMD/threads, sem GC. + +## Referências reaproveitadas + +- `/home/ovelha/android-hello` — pipeline APK C-only + assinatura v1 (openssl). +- `/home/ovelha/android-vulkan` — Vulkan puro + native_app_glue (base p/ o backend). diff --git a/apps/android/AndroidManifest.xml b/apps/android/AndroidManifest.xml new file mode 100644 index 0000000..3e4da10 --- /dev/null +++ b/apps/android/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + diff --git a/apps/android/cpp/main.c b/apps/android/cpp/main.c new file mode 100644 index 0000000..2112f7b --- /dev/null +++ b/apps/android/cpp/main.c @@ -0,0 +1,39 @@ +/* catblocks Android - NativeActivity sem Java. + * Usa android_native_app_glue (fornece ANativeActivity_onCreate, exigido pelo + * NativeActivity). Corre o interpretador de IR (catblocks) e registra a saida + * no logcat. Backend grafico continua stub (ver docs/ANDROID.md). */ +#include +#include +#include + +/* prototipos do nucleo catblocks compilado junto */ +typedef struct cb_node cb_node; +cb_node *cb_program_sum(void); +char *cb_interp_run(cb_node *root, int nvars, char **out, size_t *outlen); +void cb_node_free_all(void *p); + +static int g_ran = 0; + +static void on_app_cmd(struct android_app *app, int32_t cmd) { + if (cmd == APP_CMD_INIT_WINDOW && !g_ran) { + g_ran = 1; + cb_node *root = cb_program_sum(); + char *out = 0; size_t n = 0; + cb_interp_run(root, 4, &out, &n); + __android_log_print(ANDROID_LOG_INFO, "catblocks", + "saida do IR:\n%s", out ? out : "(vazio)"); + cb_node_free_all(0); + } +} + +void android_main(struct android_app *app) { + app->onAppCmd = on_app_cmd; + for (;;) { + int events; + struct android_poll_source *source; + while (ALooper_pollAll(-1, 0, &events, (void **)&source) >= 0) { + if (source) source->process(app, source); + if (app->destroyRequested) return; + } + } +} diff --git a/apps/android/res/values/strings.xml b/apps/android/res/values/strings.xml new file mode 100644 index 0000000..1551bbc --- /dev/null +++ b/apps/android/res/values/strings.xml @@ -0,0 +1 @@ +catblocks diff --git a/docs/ANDROID.md b/docs/ANDROID.md new file mode 100644 index 0000000..d248ddf --- /dev/null +++ b/docs/ANDROID.md @@ -0,0 +1,21 @@ +# catblocks no Android + +## Pipeline (C-only, sem Java) + +Reaproveita `/home/ovelha/android-hello`: +1. `aarch64-linux-android21-clang -shared` → `libcatblocks.so` (núcleo + NativeActivity). +2. `aapt2 compile` recursos → `aapt2 link` com o manifest. +3. adiciona a `.so` ao APK (`aapt add` / `zip`). +4. `zipalign -f 4`. +5. assinatura v1 com openssl (`/home/ovelha/android-hello/sign.sh`). + +Saída: `build/android/arm64-v8a/apk/catblocks.apk`. + +Verificação: `unzip -l` mostra `lib/arm64-v8a/libcatblocks.so`, `AndroidManifest.xml` +e `META-INF/{MANIFEST.MF,CERT.SF,CERT.RSA}`; `openssl smime -verify` → "Verification successful". + +## Backend gráfico + +GLFW não existe no Android. O backend equivalente usa `android_native_app_glue` +(Vulkan) ou EGL/GLES (OpenGL ES). A ABI do backend é a mesma dos plugins desktop +(ver `src/catblocks/plugins/backends/`). diff --git a/docs/LIMITACOES.md b/docs/LIMITACOES.md new file mode 100644 index 0000000..58f96b4 --- /dev/null +++ b/docs/LIMITACOES.md @@ -0,0 +1,10 @@ +# Limitações honestas + +- Interpretador WASM: MVP + sign-ext; **sem** tables/`call_indirect`, SIMD, threads, + GC, bulk-memory completo. Tem guarda de profundidade de recursão (64) e passo máximo. +- Editor visual auto-hospedado: apenas o esqueleto do grafo (`projects/editor.catblocks`); + não há renderização real. +- Backends Vulkan/OpenGL: ABI definida e módulos compilam como `.wasm` (stubs); + implementação real não escrita. Host headless (sem DISPLAY/vulkaninfo). +- Regressões de memória: o interpretador usa arrays estáticos de tamanho fixo + (MAXF/MaxG/...); módulos grandes podem exceder limites. diff --git a/include/catblocks/ir.h b/include/catblocks/ir.h new file mode 100644 index 0000000..9651053 --- /dev/null +++ b/include/catblocks/ir.h @@ -0,0 +1,66 @@ +/* catblocks - IR de grafo de nos (linguagem visual baseada em blocos). + * O programa e um grafo: cada No tem um tipo (op) e referencias a outros nos + * (entradas e continuacao). Todo bloco .wasm e um "plugin" cujo op mapeia para + * um export de bloco no host. */ +#ifndef CATBLOCKS_IR_H +#define CATBLOCKS_IR_H +#include +#include + +/* Operacoes base (as demais vem de plugins .wasm; op>=CB_OP_USER e plugin). */ +enum { + CB_OP_NOP = 0, + CB_OP_CONST, /* v0 = valor i32 */ + CB_OP_ADD, /* in[0]+in[1] */ + CB_OP_SUB, + CB_OP_MUL, + CB_OP_DIV, + CB_OP_MOD, + CB_OP_LT, CB_OP_GT, CB_OP_EQ, CB_OP_NE, CB_OP_LE, CB_OP_GE, + CB_OP_AND, CB_OP_OR, CB_OP_NOT, + CB_OP_VAR_GET, /* v0 = indice de variavel */ + CB_OP_VAR_SET, + CB_OP_PRINT, /* imprime in[0] */ + CB_OP_IF, /* in[0]=cond, next = entao, alt = senao */ + CB_OP_WHILE, /* in[0]=cond, next = corpo */ + CB_OP_FOR, /* v0=var, in[0]=ini, in[1]=fim, next=corpo */ + CB_OP_SEQ, /* executa next e depois alt */ + CB_OP_RETURN, + CB_OP_USER = 1000 +}; + +typedef struct cb_node cb_node; +struct cb_node { + int op; + int32_t v0; /* constante/indice de variavel */ + cb_node *in[4]; /* operandos (expressoes) */ + int nin; + cb_node *next; /* proxima instrucao na sequencia */ + cb_node *body; /* corpo (then/while/for) */ + cb_node *alt; /* ramo alternativo (senao) */ + const char *name; /* nome do plugin/bloco (para emissao) */ + void *host; /* reservado ao host/plugin */ +}; + +typedef struct { cb_node **items; int n, cap; } cb_pool; + +/* Construtor. */ +cb_node *cb_node_new(int op, int32_t v0); +void cb_node_add_in(cb_node *n, cb_node *in); +void cb_node_free_all(cb_pool *p); + +/* Avaliacao (interpretador de IR). vars aponta para um array int32. */ +typedef struct { int32_t *vars; int nvars; void (*emit)(const char*, void*); void *emit_ud; } cb_ctx; +int32_t cb_eval(cb_node *n, cb_ctx *ctx); + +/* Emissao. cb_emit_wat / cb_emit_c produzem o texto do programa a partir do + * grafo (sem depender de plugins .wasm internamente para o nucleo). */ +typedef struct { char *buf; size_t len, cap; } cb_str; +void cb_str_init(cb_str *s); +void cb_str_add(cb_str *s, const char *t); +void cb_str_free(cb_str *s); +void cb_emit_wat(cb_node *root, cb_str *out); +void cb_emit_c(cb_node *root, cb_str *out); +void cb_ir_serialize(cb_node *root, cb_str *out); + +#endif diff --git a/include/catblocks/plugin.h b/include/catblocks/plugin.h new file mode 100644 index 0000000..b6e1494 --- /dev/null +++ b/include/catblocks/plugin.h @@ -0,0 +1,49 @@ +/* catblocks - ABI de plugins .wasm. + * + * TODO modulo .wasm carregado pelo host segue este contrato: + * - exporta `int cb_abi(void)` -> versao (deve ser CB_ABI). + * - exporta `int cb_in_addr(void)` -> endereco (na memoria linear) do buffer + * de entrada, onde o host escreve o CBIR. + * - exporta `int cb_out_addr(void)` -> endereco do buffer de saida. + * - exporta `int cb_run(int in_len)` -> corre o plugin: le o CBIR do buffer de + * entrada, escreve o resultado (texto/wat/c/etc.) no buffer de saida e + * devolve o numero de bytes escritos (ou <0 em erro). + * + * Blocos (BlockLike/Renderable) exportam tambem: + * - `int on_plug(int self, int other)` -> 1 se o encaixe e aceito. + * - `int on_unplug(int self, int other)`-> 1 se o desencaixe e aceito. + * - `int on_render(int self)` -> bytes da primitiva (Renderable). + * - `int block_name(int self)` -> bytes do nome (no buffer de saida). + * - `int block_color(int self)` -> cor RGB empacotada (0xRRGGBB). + * + * Convencao de memoria: o host reserva 64 KiB para o buffer de entrada e 64 KiB + * para a saida, em enderecos escolhidos pelo plugin (>= 0x10000). + */ +#ifndef CATBLOCKS_PLUGIN_H +#define CATBLOCKS_PLUGIN_H +#include "catblocks/wasm.h" + +#define CB_ABI 1 + +typedef struct cb_plugin cb_plugin; + +/* Carrega um plugin .wasm de um ficheiro; devolve NULL com err preenchido. */ +cb_plugin *cb_plugin_load_file(const char *path, char *err, size_t errcap); +cb_plugin *cb_plugin_load_bytes(const uint8_t *bytes, size_t len, char *err, size_t errcap); +void cb_plugin_free(cb_plugin *p); + +/* Corre o plugin sobre o texto ir; devolve a saida (malloc) e o tamanho. */ +char *cb_plugin_run(cb_plugin *p, const char *ir, size_t ir_len, size_t *out_len); +/* Le um export i32 simples (0 se ausente). */ +int cb_plugin_export_i32(cb_plugin *p, const char *name, int arg); +/* Corre e devolve a saida como string (chama cb_run com ir). */ +const char *cb_plugin_error(cb_plugin *p); +/* buffer de saida e memoria do plugin */ +char *cb_plugin_outbuf(cb_plugin *p, int *out_addr, uint32_t *mem_size); +wasm_inst *cb_plugin_inst(cb_plugin *p); + +/* Interfaces que um plugin assina. */ +int cb_plugin_has_blocklike(cb_plugin *p); +int cb_plugin_has_renderable(cb_plugin *p); + +#endif diff --git a/include/catblocks/programs.h b/include/catblocks/programs.h new file mode 100644 index 0000000..5aaaec2 --- /dev/null +++ b/include/catblocks/programs.h @@ -0,0 +1,6 @@ +#ifndef CATBLOCKS_PROGRAMS_H +#define CATBLOCKS_PROGRAMS_H +#include "catblocks/ir.h" +cb_node *cb_const(int32_t v); +cb_node *cb_program_sum(void); +#endif diff --git a/include/catblocks/wasm.h b/include/catblocks/wasm.h new file mode 100644 index 0000000..5f35eec --- /dev/null +++ b/include/catblocks/wasm.h @@ -0,0 +1,41 @@ +/* catblocks – minimal WebAssembly (MVP + sign-ext + sat-trunc + bulk-mem) interpreter. + * Host-side only. No JIT, no tables/call_indirect, no SIMD, no threads. */ +#ifndef CATBLOCKS_WASM_H +#define CATBLOCKS_WASM_H +#include +#include + +typedef uint64_t wval; /* i32/f32 in low 32 bits (bit pattern), i64/f64 full */ +enum { WT_I32 = 0x7F, WT_I64 = 0x7E, WT_F32 = 0x7D, WT_F64 = 0x7C }; +enum { WK_FUNC = 0, WK_TABLE = 1, WK_MEM = 2, WK_GLOBAL = 3 }; + +typedef struct wasm_module wasm_module; +typedef struct wasm_inst wasm_inst; +typedef int (*wasm_hostfn)(wasm_inst *in, const wval *args, wval *ret, void *ud); +typedef struct { const char *mod, *name; wasm_hostfn fn; void *ud; } wasm_import_def; + +typedef struct { int np, nr; uint8_t p[8], r[2]; } wasm_sig; + +/* bytes are copied. On failure returns NULL and fills err. */ +wasm_module *wasm_load(const uint8_t *bytes, size_t len, char *err, size_t errcap); +void wasm_module_free(wasm_module *m); +int wasm_export_sig(const wasm_module *m, const char *name, int kind, wasm_sig *sig); /* 1 if found */ +int wasm_import_count(const wasm_module *m); +void wasm_import_name(const wasm_module *m, int i, const char **mod, const char **name); + +wasm_inst *wasm_instantiate(wasm_module *m, const wasm_import_def *imps, int nimps, + uint32_t max_mem_pages, char *err, size_t errcap); +void wasm_free(wasm_inst *in); +void *wasm_user(wasm_inst *in); +void wasm_set_user(wasm_inst *in, void *u); +uint8_t *wasm_memory(wasm_inst *in, uint32_t *size); +/* returns 0 ok, nonzero on trap (message via wasm_error) */ +int wasm_call(wasm_inst *in, const char *export_name, const wval *args, int nargs, wval *ret); +const char *wasm_error(wasm_inst *in); + +static inline wval wv_i32(int32_t v){ return (uint32_t)v; } +static inline wval wv_f64(double d){ wval v; __builtin_memcpy(&v,&d,8); return v; } +static inline double wv_to_f64(wval v){ double d; __builtin_memcpy(&d,&v,8); return d; } +static inline wval wv_f32(float f){ uint32_t u; __builtin_memcpy(&u,&f,4); return u; } +static inline float wv_to_f32(wval v){ uint32_t u=(uint32_t)v; float f; __builtin_memcpy(&f,&u,4); return f; } +#endif diff --git a/projects/editor.catblocks b/projects/editor.catblocks new file mode 100644 index 0000000..b725648 --- /dev/null +++ b/projects/editor.catblocks @@ -0,0 +1,20 @@ +# catblocks project: editor visual auto-hospedado +# O editor e' ele mesmo um programa catblocks: um grafo de blocos que +# desenha a UI (paleta de blocos, canvas, fios de encaixe) usando um +# backend grafico escolhido como plugin .wasm (vulkan no desktop/opengl). +# +# Formato CBIR (v1). Linhas: idx op v0 nin c0 c1 c2 c3 next body alt +# Ops: 1=const 15=not 16=var_get 17=var_set 18=print 19=if 20=while 21=for +# 2=add 3=sub 4=mul 7=lt 8=gt 9=eq +var 8 +# v0 = frame; v1 = bloco selecionado; v2 = x; v3 = y; v4 = i; v5 = n +0 17 0 1 11 -1 -1 -1 1 -1 -1 +# while (v0) { renderiza } +1 20 0 1 4 -1 -1 -1 2 3 -1 +# corpo: desenha paleta (chamada a plugin backend via print de teste) +2 18 0 1 12 -1 -1 -1 -1 -1 -1 +3 17 0 1 13 -1 -1 -1 -1 -1 -1 +4 16 0 0 -1 -1 -1 -1 -1 -1 -1 +11 1 0 0 -1 -1 -1 -1 -1 -1 -1 +12 1 7 0 -1 -1 -1 -1 -1 -1 -1 +13 1 0 0 -1 -1 -1 -1 -1 -1 -1 diff --git a/scripts/blockflags.sh b/scripts/blockflags.sh new file mode 100755 index 0000000..87e26df --- /dev/null +++ b/scripts/blockflags.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# emite as flags -D de cada bloco (nome, cor, categoria, render, plugs) +case "$1" in + add) echo '-DCB_NAME="\"+\"" -DCB_COLOR=0x4C97FF -DCB_CAT=0 -DCB_RENDER=1 -DCB_PLUGS=1';; + subtract) echo '-DCB_NAME="\"-\"" -DCB_COLOR=0x4C97FF -DCB_CAT=0 -DCB_RENDER=1 -DCB_PLUGS=1';; + multiply) echo '-DCB_NAME="\"*\"" -DCB_COLOR=0x4C97FF -DCB_CAT=0 -DCB_RENDER=1 -DCB_PLUGS=1';; + divide) echo '-DCB_NAME="\"/\"" -DCB_COLOR=0x4C97FF -DCB_CAT=0 -DCB_RENDER=1 -DCB_PLUGS=1';; + and) echo '-DCB_NAME="\"and\"" -DCB_COLOR=0x59C059 -DCB_CAT=1 -DCB_RENDER=1 -DCB_PLUGS=1';; + or) echo '-DCB_NAME="\"or\"" -DCB_COLOR=0x59C059 -DCB_CAT=1 -DCB_RENDER=1 -DCB_PLUGS=1';; + not) echo '-DCB_NAME="\"not\"" -DCB_COLOR=0x59C059 -DCB_CAT=1 -DCB_RENDER=1 -DCB_PLUGS=1';; + if) echo '-DCB_NAME="\"if\"" -DCB_COLOR=0xFFAB19 -DCB_CAT=2 -DCB_RENDER=1 -DCB_PLUGS=1';; + else) echo '-DCB_NAME="\"else\"" -DCB_COLOR=0xFFAB19 -DCB_CAT=2 -DCB_RENDER=1 -DCB_PLUGS=0';; + while) echo '-DCB_NAME="\"while\"" -DCB_COLOR=0xFFAB19 -DCB_CAT=2 -DCB_RENDER=1 -DCB_PLUGS=1';; + for) echo '-DCB_NAME="\"for\"" -DCB_COLOR=0xFFAB19 -DCB_CAT=2 -DCB_RENDER=1 -DCB_PLUGS=1';; + when_start)echo '-DCB_NAME="\"when_start\"" -DCB_COLOR=0xFFBF00 -DCB_CAT=3 -DCB_RENDER=0 -DCB_PLUGS=0';; + *) echo '-DCB_NAME="\"block\"" -DCB_COLOR=0x4C97FF -DCB_CAT=0 -DCB_RENDER=1 -DCB_PLUGS=1';; +esac diff --git a/scripts/build_android.sh b/scripts/build_android.sh new file mode 100755 index 0000000..e2aece2 --- /dev/null +++ b/scripts/build_android.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# catblocks Android: pipeline C-only reaproveitado de /home/ovelha/android-hello. +# CORRIGIDO: liga android_native_app_glue (exporta ANativeActivity_onCreate, que o +# NativeActivity exige) e assina com apksigner (v1+v2+v3), nao so v1. +set -euo pipefail + +SDK="${ANDROID_HOME:-/home/ovelha/android-sdk}" +BT="$SDK/build-tools/34" +PLATFORM="$SDK/platforms/35/android.jar" +NDK="$SDK/ndk/android-ndk-r26d" +TC="$NDK/toolchains/llvm/prebuilt/linux-x86_64" +CC="$TC/bin/aarch64-linux-android21-clang" +GLUE="$NDK/sources/android/native_app_glue" + +PROJ="/home/ovelha/catblocks" +OUT="$PROJ/build/android/arm64-v8a" +ABI="arm64-v8a" +APK="$PROJ/build/android/$ABI/apk/catblocks.apk" +KS="$HOME/.android/debug.keystore" + +rm -rf "$OUT"; mkdir -p "$OUT/res" "$OUT/lib/$ABI" "$OUT/gen" "$(dirname "$APK")" + +echo "== 1. compilar C (nucleo + NativeActivity + glue) ==" +"$CC" -shared -fPIC -O2 -I"$PROJ/include" -I"$GLUE" \ + -o "$OUT/lib/$ABI/libcatblocks.so" \ + "$PROJ/apps/android/cpp/main.c" \ + "$GLUE/android_native_app_glue.c" \ + "$PROJ/src/catblocks/ir.c" \ + "$PROJ/src/catblocks/interp.c" \ + "$PROJ/src/catblocks/programs.c" \ + -Wl,-u,ANativeActivity_onCreate \ + -landroid -llog -ldl + +echo "== checar simbolo exigido pelo NativeActivity ==" +readelf -sW "$OUT/lib/$ABI/libcatblocks.so" | grep -q ANativeActivity_onCreate \ + || { echo "ERRO: ANativeActivity_onCreate ausente"; exit 1; } +echo " ANativeActivity_onCreate: OK" + +echo "== 2. compilar recursos (aapt2 compile) ==" +"$BT/aapt2" compile --dir "$PROJ/apps/android/res" -o "$OUT/res.zip" + +echo "== 3. linkar recursos + manifest ==" +"$BT/aapt2" link \ + -o "$OUT/base.apk" \ + -I "$PLATFORM" \ + --manifest "$PROJ/apps/android/AndroidManifest.xml" \ + --java "$OUT/gen" \ + "$OUT/res.zip" + +echo "== 4. adicionar a .so ao APK ==" +cd "$OUT" +cp base.apk unsigned.apk +zip -q -j unsigned.apk "lib/$ABI/libcatblocks.so" + +echo "== 5. zipalign ==" +"$BT/zipalign" -f -p 4 unsigned.apk aligned.apk + +echo "== 6. assinar (apksigner: v1+v2+v3) ==" +"$BT/apksigner" sign \ + --ks "$KS" --ks-pass pass:android \ + --ks-key-alias androiddebugkey --key-pass pass:android \ + --v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \ + --out "$APK" aligned.apk + +echo "== 7. verificar ==" +"$BT/apksigner" verify --verbose "$APK" | head -8 +echo "== APK: $APK ==" +ls -l "$APK" diff --git a/src/catblocks/interp.c b/src/catblocks/interp.c new file mode 100644 index 0000000..b1eb4f2 --- /dev/null +++ b/src/catblocks/interp.c @@ -0,0 +1,26 @@ +/* catblocks - interpretador de IR: executa o grafo e captura a saida. */ +#include "catblocks/ir.h" +#include +#include + +typedef struct { char *buf; size_t len, cap; } outbuf; + +static void out_emit(const char *chunk, void *ud) { + outbuf *o = (outbuf*)ud; + size_t n = strlen(chunk); + if (o->len + n + 1 > o->cap) { while (o->len + n + 1 > o->cap) o->cap = o->cap ? o->cap*2 : 256; o->buf = realloc(o->buf, o->cap); } + memcpy(o->buf + o->len, chunk, n); o->len += n; o->buf[o->len] = 0; +} + +/* Executa o grafo root; devolve a saida (malloc, chamador liberta) e o total + * de bytes em *outlen. vars: array de nvars inteiros. */ +char *cb_interp_run(cb_node *root, int nvars, char **out, size_t *outlen) { + outbuf o = {0}; + int32_t *vars = calloc(nvars ? nvars : 1, sizeof(int32_t)); + cb_ctx ctx = { vars, nvars, out_emit, &o }; + cb_eval(root, &ctx); + free(vars); + if (out) *out = o.buf; else free(o.buf); + if (outlen) *outlen = o.len; + return o.buf; +} diff --git a/src/catblocks/ir.c b/src/catblocks/ir.c new file mode 100644 index 0000000..ca129da --- /dev/null +++ b/src/catblocks/ir.c @@ -0,0 +1,261 @@ +/* catblocks - IR: grafo de nos, avaliador e emissores wat/c. */ +#include "catblocks/ir.h" +#include +#include +#include + +/* ---------- alocacao de nos ---------- */ +static cb_node **g_allocs; static int g_nalloc, g_capalloc; +static void reg(cb_node *n) { + if (g_nalloc == g_capalloc) { g_capalloc = g_capalloc ? g_capalloc*2 : 64; g_allocs = realloc(g_allocs, g_capalloc*sizeof(*g_allocs)); } + g_allocs[g_nalloc++] = n; +} +cb_node *cb_node_new(int op, int32_t v0) { + cb_node *n = calloc(1, sizeof(cb_node)); + n->op = op; n->v0 = v0; reg(n); return n; +} +void cb_node_add_in(cb_node *n, cb_node *in) { if (n->nin < 4) n->in[n->nin++] = in; } +void cb_node_free_all(cb_pool *p) { (void)p; for (int i = 0; i < g_nalloc; i++) free(g_allocs[i]); + free(g_allocs); g_allocs = NULL; g_nalloc = g_capalloc = 0; } + +/* ---------- string builder ---------- */ +void cb_str_init(cb_str *s) { s->cap = 256; s->len = 0; s->buf = malloc(s->cap); s->buf[0] = 0; } +void cb_str_add(cb_str *s, const char *t) { + size_t n = strlen(t); + if (s->len + n + 1 > s->cap) { while (s->len+n+1 > s->cap) s->cap *= 2; s->buf = realloc(s->buf, s->cap); } + memcpy(s->buf + s->len, t, n+1); s->len += n; +} +void cb_str_free(cb_str *s) { free(s->buf); s->buf = NULL; s->len = s->cap = 0; } + +/* ---------- avaliador ---------- */ +static int32_t ev(cb_node *n, cb_ctx *c) { + if (!n) return 0; + switch (n->op) { + case CB_OP_CONST: return n->v0; + case CB_OP_ADD: return ev(n->in[0],c) + ev(n->in[1],c); + case CB_OP_SUB: return ev(n->in[0],c) - ev(n->in[1],c); + case CB_OP_MUL: return ev(n->in[0],c) * ev(n->in[1],c); + case CB_OP_DIV: { int32_t d = ev(n->in[1],c); return d ? ev(n->in[0],c)/d : 0; } + case CB_OP_MOD: { int32_t d = ev(n->in[1],c); return d ? ev(n->in[0],c)%d : 0; } + case CB_OP_LT: return ev(n->in[0],c) < ev(n->in[1],c); + case CB_OP_GT: return ev(n->in[0],c) > ev(n->in[1],c); + case CB_OP_EQ: return ev(n->in[0],c) == ev(n->in[1],c); + case CB_OP_NE: return ev(n->in[0],c) != ev(n->in[1],c); + case CB_OP_LE: return ev(n->in[0],c) <= ev(n->in[1],c); + case CB_OP_GE: return ev(n->in[0],c) >= ev(n->in[1],c); + case CB_OP_AND: return ev(n->in[0],c) && ev(n->in[1],c); + case CB_OP_OR: return ev(n->in[0],c) || ev(n->in[1],c); + case CB_OP_NOT: return !ev(n->in[0],c); + case CB_OP_VAR_GET: return (n->v0 >= 0 && n->v0 < c->nvars) ? c->vars[n->v0] : 0; + case CB_OP_VAR_SET: { int32_t v = ev(n->in[0],c); if (n->v0>=0 && n->v0nvars) c->vars[n->v0]=v; return v; } + default: return 0; + } +} + +static long g_steps; +static int run_stmt(cb_node *n, cb_ctx *c) { + for (; n; n = n->next) { + if (++g_steps > 50000000L) return -1; + switch (n->op) { + case CB_OP_PRINT: { + int32_t v = ev(n->in[0], c); + char buf[64]; snprintf(buf, sizeof buf, "%d\n", (int)v); + if (c->emit) c->emit(buf, c->emit_ud); + break; + } + case CB_OP_VAR_SET: (void)ev(n, c); break; + case CB_OP_IF: if (ev(n->in[0],c)) run_stmt(n->body, c); else run_stmt(n->alt, c); break; + case CB_OP_WHILE: while (ev(n->in[0],c)) { if (run_stmt(n->body, c)) return -1; } break; + case CB_OP_FOR: { + int32_t i = ev(n->in[0], c), end = ev(n->in[1], c); + for (; i < end; i++) { + if (n->v0 >= 0 && n->v0 < c->nvars) c->vars[n->v0] = i; + if (run_stmt(n->body, c)) return -1; + } + if (n->v0 >= 0 && n->v0 < c->nvars) c->vars[n->v0] = i; + break; + } + case CB_OP_RETURN: return 1; + default: (void)ev(n, c); break; + } + } + return 0; +} + +int32_t cb_eval(cb_node *n, cb_ctx *c) { g_steps = 0; run_stmt(n, c); return 0; } + +/* ---------- emissores ---------- */ +static const char *wat_binop(int op) { + switch (op) { + case CB_OP_ADD: return "i32.add"; case CB_OP_SUB: return "i32.sub"; + case CB_OP_MUL: return "i32.mul"; case CB_OP_DIV: return "i32.div_s"; + case CB_OP_MOD: return "i32.rem_s"; case CB_OP_LT: return "i32.lt_s"; + case CB_OP_GT: return "i32.gt_s"; case CB_OP_EQ: return "i32.eq"; + case CB_OP_NE: return "i32.ne"; case CB_OP_LE: return "i32.le_s"; + case CB_OP_GE: return "i32.ge_s"; case CB_OP_AND: return "i32.and"; + case CB_OP_OR: return "i32.or"; + default: return NULL; + } +} +static const char *c_binop(int op) { + switch (op) { + case CB_OP_ADD: return "+"; case CB_OP_SUB: return "-"; case CB_OP_MUL: return "*"; + case CB_OP_DIV: return "/"; case CB_OP_MOD: return "%"; case CB_OP_LT: return "<"; + case CB_OP_GT: return ">"; case CB_OP_EQ: return "=="; case CB_OP_NE: return "!="; + case CB_OP_LE: return "<="; case CB_OP_GE: return ">="; case CB_OP_AND: return "&&"; + case CB_OP_OR: return "||"; default: return NULL; + } +} +/* expressoes: wat (postfix) e c (infix) */ +static void ew(cb_node *n, cb_str *o) { + if (!n) { cb_str_add(o, "i32.const 0\n"); return; } + char t[96]; + switch (n->op) { + case CB_OP_CONST: snprintf(t,sizeof t,"i32.const %d\n",(int)n->v0); cb_str_add(o,t); return; + case CB_OP_VAR_GET: snprintf(t,sizeof t,"local.get $v%d\n",(int)n->v0); cb_str_add(o,t); return; + case CB_OP_NOT: ew(n->in[0],o); cb_str_add(o,"i32.eqz\n"); return; + default: { + const char *b = wat_binop(n->op); + if (b) { ew(n->in[0],o); ew(n->in[1],o); cb_str_add(o,b); cb_str_add(o,"\n"); return; } + cb_str_add(o,"i32.const 0\n"); return; + }} +} +static void ec(cb_node *n, cb_str *o) { + if (!n) { cb_str_add(o,"0"); return; } + char t[96]; + switch (n->op) { + case CB_OP_CONST: snprintf(t,sizeof t,"%d",(int)n->v0); cb_str_add(o,t); return; + case CB_OP_VAR_GET: snprintf(t,sizeof t,"v%d",(int)n->v0); cb_str_add(o,t); return; + case CB_OP_NOT: cb_str_add(o,"!("); ec(n->in[0],o); cb_str_add(o,")") ; return; + default: { + const char *b = c_binop(n->op); + if (b) { cb_str_add(o,"("); ec(n->in[0],o); cb_str_add(o,b); ec(n->in[1],o); cb_str_add(o,")"); return; } + cb_str_add(o,"0"); return; + }} +} + +/* lista de instrucoes */ +static void list_w(cb_node *n, cb_str *o, int ind); +static void list_c(cb_node *n, cb_str *o, int ind); + +static void indent(cb_str *o, int ind){ for(int i=0;iop) { + case CB_OP_VAR_SET: indent(o,ind); ew(n->in[0],o); + snprintf(t,sizeof t,"local.set $v%d\n",(int)n->v0); cb_str_add(o,t); break; + case CB_OP_PRINT: indent(o,ind); ew(n->in[0],o); cb_str_add(o,"call $print\n"); break; + case CB_OP_IF: + indent(o,ind); cb_str_add(o,"(if "); ew(n->in[0],o); cb_str_add(o,"(then\n"); + list_w(n->body,o,ind+1); indent(o,ind); cb_str_add(o,")"); + if (n->alt) { cb_str_add(o,"(else\n"); list_w(n->alt,o,ind+1); indent(o,ind); cb_str_add(o,")"); } + cb_str_add(o,")\n"); break; + case CB_OP_WHILE: + indent(o,ind); cb_str_add(o,"(block $ex\n"); indent(o,ind+1); cb_str_add(o,"(loop $lp\n"); + indent(o,ind+2); ew(n->in[0],o); cb_str_add(o,"i32.eqz\n"); indent(o,ind+2); cb_str_add(o,"br_if $ex\n"); + list_w(n->body,o,ind+2); indent(o,ind+2); cb_str_add(o,"br $lp\n"); + indent(o,ind+1); cb_str_add(o,")\n"); indent(o,ind); cb_str_add(o,")\n"); break; + case CB_OP_FOR: + snprintf(t,sizeof t,"local.set $v%d\n",(int)n->v0); + indent(o,ind); ew(n->in[0],o); cb_str_add(o,t); + indent(o,ind); cb_str_add(o,"(block $ex\n"); indent(o,ind+1); cb_str_add(o,"(loop $lp\n"); + indent(o,ind+2); snprintf(t,sizeof t,"local.get $v%d\n",(int)n->v0); cb_str_add(o,t); + ew(n->in[1],o); cb_str_add(o,"i32.ge_s\n"); indent(o,ind+2); cb_str_add(o,"br_if $ex\n"); + list_w(n->body,o,ind+2); + indent(o,ind+2); snprintf(t,sizeof t,"local.get $v%d\ni32.const 1\ni32.add\nlocal.set $v%d\n",(int)n->v0,(int)n->v0); cb_str_add(o,t); + indent(o,ind+2); cb_str_add(o,"br $lp\n"); + indent(o,ind+1); cb_str_add(o,")\n"); indent(o,ind); cb_str_add(o,")\n"); break; + default: break; + } +} +static void list_w(cb_node *n, cb_str *o, int ind){ for(;n;n=n->next) stmt_w(n,o,ind); } + +static void stmt_c(cb_node *n, cb_str *o, int ind) { + char t[128]; + switch (n->op) { + case CB_OP_VAR_SET: indent(o,ind); snprintf(t,sizeof t,"v%d = ",(int)n->v0); cb_str_add(o,t); ec(n->in[0],o); cb_str_add(o,";\n"); break; + case CB_OP_PRINT: indent(o,ind); cb_str_add(o,"cb_print("); ec(n->in[0],o); cb_str_add(o,");\n"); break; + case CB_OP_IF: + indent(o,ind); cb_str_add(o,"if ("); ec(n->in[0],o); cb_str_add(o,") {\n"); + list_c(n->body,o,ind+1); indent(o,ind); cb_str_add(o,"}"); + if (n->alt) { cb_str_add(o," else {\n"); list_c(n->alt,o,ind+1); indent(o,ind); cb_str_add(o,"}"); } + cb_str_add(o,"\n"); break; + case CB_OP_WHILE: + indent(o,ind); cb_str_add(o,"while ("); ec(n->in[0],o); cb_str_add(o,") {\n"); + list_c(n->body,o,ind+1); indent(o,ind); cb_str_add(o,"}\n"); break; + case CB_OP_FOR: + indent(o,ind); snprintf(t,sizeof t,"for (v%d = ",(int)n->v0); cb_str_add(o,t); ec(n->in[0],o); + snprintf(t,sizeof t,"; v%d < ",(int)n->v0); cb_str_add(o,t); ec(n->in[1],o); + snprintf(t,sizeof t,"; v%d++) {\n",(int)n->v0); cb_str_add(o,t); + list_c(n->body,o,ind+1); indent(o,ind); cb_str_add(o,"}\n"); break; + default: break; + } +} +static void list_c(cb_node *n, cb_str *o, int ind){ for(;n;n=n->next) stmt_c(n,o,ind); } + +/* descobre o maior indice de variavel usado */ +static void scan_vars(cb_node *n, int *mx) { + for (; n; n = n->next) { + if ((n->op==CB_OP_VAR_SET||n->op==CB_OP_VAR_GET||n->op==CB_OP_FOR) && n->v0>=*mx) *mx=n->v0+1; + for (int i=0;inin;i++) scan_vars(n->in[i],mx); + scan_vars(n->body,mx); scan_vars(n->alt,mx); + } +} + +void cb_emit_wat(cb_node *root, cb_str *o) { + int nv=0; scan_vars(root,&nv); + cb_str_add(o,"(module\n"); + cb_str_add(o," (import \"catblocks\" \"print\" (func $print (param i32)))\n"); + cb_str_add(o," (func $main (export \"main\")\n"); + for (int i=0;iC */\n#include \n"); + cb_str_add(o,"static void cb_print(int v){ printf(\"%d\\n\", v); }\n"); + cb_str_add(o,"int main(void){\n"); + for (int i=0;i + * + * indices -1 = nenhum. */ +static int collect(cb_node *n, cb_node **arr, int *n_, int cap) { + if (!n) return -1; + for (int i = 0; i < *n_; i++) if (arr[i] == n) return i; + int idx = (*n_)++; + if (idx >= cap) return idx; + arr[idx] = n; + collect(n->next, arr, n_, cap); + collect(n->body, arr, n_, cap); + collect(n->alt, arr, n_, cap); + for (int i = 0; i < n->nin; i++) collect(n->in[i], arr, n_, cap); + return idx; +} +void cb_ir_serialize(cb_node *root, cb_str *o) { + int nv = 0; scan_vars(root, &nv); + static cb_node *arr[4096]; + int n = 0; collect(root, arr, &n, 4096); + char t[256]; + cb_str_add(o, "# catblocks IR v1\n"); + snprintf(t, sizeof t, "var %d\n", nv); cb_str_add(o, t); + for (int i = 0; i < n; i++) { + cb_node *x = arr[i]; + int c[4] = {-1,-1,-1,-1}; + for (int k = 0; k < x->nin && k < 4; k++) c[k] = collect(x->in[k], arr, &n, 4096); + int nx = collect(x->next, arr, &n, 4096); + int bd = collect(x->body, arr, &n, 4096); + int al = collect(x->alt, arr, &n, 4096); + snprintf(t, sizeof t, "%d %d %d %d %d %d %d %d %d %d %d\n", + i, x->op, x->v0, x->nin, c[0], c[1], c[2], c[3], nx, bd, al); + cb_str_add(o, t); + } +} diff --git a/src/catblocks/plugin.c b/src/catblocks/plugin.c new file mode 100644 index 0000000..5c7b0cf --- /dev/null +++ b/src/catblocks/plugin.c @@ -0,0 +1,93 @@ +/* catblocks - carregador/executor de plugins .wasm (ABI em plugin.h). */ +#include "catblocks/plugin.h" +#include +#include +#include + +struct cb_plugin { + wasm_module *m; + wasm_inst *in; + uint32_t in_addr, out_addr; + char err[200]; +}; + +static int get_addr(wasm_inst *in, const char *name, uint32_t *out) { + wval r = 0; + if (wasm_call(in, name, NULL, 0, &r)) return 0; + *out = (uint32_t)r; return 1; +} + +cb_plugin *cb_plugin_load_bytes(const uint8_t *bytes, size_t len, char *err, size_t errcap) { + cb_plugin *p = calloc(1, sizeof(cb_plugin)); + p->m = wasm_load(bytes, len, err, errcap); + if (!p->m) { free(p); return NULL; } + p->in = wasm_instantiate(p->m, NULL, 0, 64, err, errcap); + if (!p->in) { wasm_module_free(p->m); free(p); return NULL; } + if (!get_addr(p->in, "cb_in_addr", &p->in_addr) || + !get_addr(p->in, "cb_out_addr", &p->out_addr)) { + snprintf(err, errcap, "plugin sem cb_in_addr/cb_out_addr"); + wasm_free(p->in); wasm_module_free(p->m); free(p); return NULL; + } + return p; +} + +cb_plugin *cb_plugin_load_file(const char *path, char *err, size_t errcap) { + FILE *f = fopen(path, "rb"); + if (!f) { snprintf(err, errcap, "nao abri %s", path); return NULL; } + fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET); + uint8_t *b = malloc(n ? n : 1); + if (fread(b, 1, n, f) != (size_t)n) { fclose(f); free(b); snprintf(err,errcap,"leitura falhou"); return NULL; } + fclose(f); + cb_plugin *p = cb_plugin_load_bytes(b, n, err, errcap); + free(b); + return p; +} + +void cb_plugin_free(cb_plugin *p) { + if (!p) return; + wasm_free(p->in); wasm_module_free(p->m); free(p); +} + +const char *cb_plugin_error(cb_plugin *p) { return p ? p->err : ""; } +wasm_inst *cb_plugin_inst(cb_plugin *p) { return p ? p->in : NULL; } +char *cb_plugin_outbuf(cb_plugin *p, int *out_addr, uint32_t *mem_size) { + if (!p) return NULL; + if (out_addr) *out_addr = (int)p->out_addr; + if (mem_size) { uint32_t s = 0; wasm_memory(p->in, &s); *mem_size = s; } + uint32_t s2 = 0; return (char*)wasm_memory(p->in, &s2); +} + +char *cb_plugin_run(cb_plugin *p, const char *ir, size_t ir_len, size_t *out_len) { + uint32_t sz = 0; + uint8_t *mem = wasm_memory(p->in, &sz); + if (p->in_addr + ir_len > sz || p->out_addr + 1 > sz) { + snprintf(p->err, sizeof p->err, "buffers fora da memoria"); return NULL; + } + memcpy(mem + p->in_addr, ir, ir_len); + mem[ir_len + 0] = 0; + wval a = wv_i32((int32_t)ir_len), r = 0; + if (wasm_call(p->in, "cb_run", &a, 1, &r)) { + snprintf(p->err, sizeof p->err, "cb_run: %s", wasm_error(p->in)); return NULL; + } + int32_t n = (int32_t)r; + if (n < 0) { snprintf(p->err, sizeof p->err, "plugin devolveu erro %d", n); return NULL; } + if ((uint32_t)n > sz - p->out_addr) n = sz - p->out_addr; + char *o = malloc(n + 1); + memcpy(o, mem + p->out_addr, n); o[n] = 0; + if (out_len) *out_len = n; + return o; +} + +int cb_plugin_export_i32(cb_plugin *p, const char *name, int arg) { + wval a = wv_i32(arg), r = 0; + if (wasm_call(p->in, name, &a, 1, &r)) return 0; + return (int32_t)r; +} + +int cb_plugin_has_blocklike(cb_plugin *p) { + return wasm_export_sig(p->m, "on_plug", WK_FUNC, NULL) && + wasm_export_sig(p->m, "on_unplug", WK_FUNC, NULL); +} +int cb_plugin_has_renderable(cb_plugin *p) { + return wasm_export_sig(p->m, "on_render", WK_FUNC, NULL); +} diff --git a/src/catblocks/plugins/backends/opengl/backend.c b/src/catblocks/plugins/backends/opengl/backend.c new file mode 100644 index 0000000..e401f40 --- /dev/null +++ b/src/catblocks/plugins/backends/opengl/backend.c @@ -0,0 +1,10 @@ +/* catblocks - backend grafico OpenGL (esboco de plugin .wasm). Mesma ABI do Vulkan. */ +#include +int backend_init(int w, int h) { (void)w; (void)h; return 0; } +void backend_clear(int rgb) { (void)rgb; } +int backend_draw_rect(int x,int y,int w,int h,int rgb) { + (void)x; (void)y; (void)w; (void)h; (void)rgb; return 0; } +int backend_draw_line(int x0,int y0,int x1,int y1,int rgb) { + (void)x0; (void)y0; (void)x1; (void)y1; (void)rgb; return 0; } +int backend_present(void) { return 0; } +void backend_shutdown(void) { } diff --git a/src/catblocks/plugins/backends/vulkan/backend.c b/src/catblocks/plugins/backends/vulkan/backend.c new file mode 100644 index 0000000..f7b608f --- /dev/null +++ b/src/catblocks/plugins/backends/vulkan/backend.c @@ -0,0 +1,19 @@ +/* catblocks - backend grafico Vulkan (esboco de plugin .wasm). + * ABI do backend (plugin .wasm): + * int backend_init(int width, int height); -> 0 ok + * void backend_clear(int rgb); + * int backend_draw_rect(int x,int y,int w,int h,int rgb); + * int backend_draw_line(int x0,int y0,int x1,int y1,int rgb); + * int backend_present(void); + * void backend_shutdown(void); + * O editor auto-hospedado chama estas via imports do host. O backend real usa + * Vulkan + GLFW (desktop) ou android_native_app_glue (Android). */ +#include +int backend_init(int w, int h) { (void)w; (void)h; return 0; } +void backend_clear(int rgb) { (void)rgb; } +int backend_draw_rect(int x,int y,int w,int h,int rgb) { + (void)x; (void)y; (void)w; (void)h; (void)rgb; return 0; } +int backend_draw_line(int x0,int y0,int x1,int y1,int rgb) { + (void)x0; (void)y0; (void)x1; (void)y1; (void)rgb; return 0; } +int backend_present(void) { return 0; } +void backend_shutdown(void) { } diff --git a/src/catblocks/plugins/blocks/block_template.c b/src/catblocks/plugins/blocks/block_template.c new file mode 100644 index 0000000..35a58c0 --- /dev/null +++ b/src/catblocks/plugins/blocks/block_template.c @@ -0,0 +1,66 @@ +/* catblocks - bloco .wasm generico (template). + * Compila-se varias vezes com -DCB_KIND=... -DCB_NAME="..." -DCB_COLOR=0xRRGGBB. + * ABI: + * int cb_abi(void); -> versao + * int cb_in_addr(void); -> buffer de entrada + * int cb_out_addr(void); -> buffer de saida + * int cb_run(int in_len); -> avaliacao (expr) do bloco + * int block_name(int self); -> bytes do nome no buffer de saida + * int block_color(int self); -> cor RRGGBB + * int block_cat(int self); -> categoria (0 aritmetica..) + * int on_plug(int self, int oth)-> 1 se aceita encaixe inferior + * int on_unplug(int self,int oth)-> 1 se aceita desencaixe + * int on_render(int self); -> bytes da primitiva (Renderable) ou 0 + */ +char g_in[4096]; +char g_out[4096]; + +#ifndef CB_NAME +#define CB_NAME "block" +#endif +#ifndef CB_COLOR +#define CB_COLOR 0x4C97FF +#endif +#ifndef CB_CAT +#define CB_CAT 0 +#endif +#ifndef CB_PLUGS +#define CB_PLUGS 1 +#endif +#ifndef CB_RENDER +#define CB_RENDER 0 +#endif + +int cb_abi(void){ return 1; } +int cb_in_addr(void){ return (int)(unsigned long)g_in; } +int cb_out_addr(void){ return (int)(unsigned long)g_out; } + +static int slen(const char *s){ int n=0; while(s[n]) n++; return n; } +static void scopy(char *d, const char *s){ int i=0; while(s[i]){ d[i]=s[i]; i++; } d[i]=0; } + +int block_name(int self){ (void)self; scopy(g_out, CB_NAME); return slen(CB_NAME); } +int block_color(int self){ (void)self; return CB_COLOR; } +int block_cat(int self){ (void)self; return CB_CAT; } +int on_plug(int self, int oth){ (void)self;(void)oth; return CB_PLUGS; } +int on_unplug(int self, int oth){ (void)self;(void)oth; return CB_PLUGS; } + +#if CB_RENDER +/* Renderable: escreve uma primitiva simples no buffer de saida: + * "rect " (estilo Scratch). */ +static int i2s(int v, char *d){ char b[16]; int n=0,k=0; if(v<0){ d[k++]='-'; v=-v; } + if(v==0) b[n++]='0'; while(v>0){ b[n++]='0'+v%10; v/=10; } + for(int i=n-1;i>=0;i--) d[k++]=b[i]; d[k]=0; return k; } +int on_render(int self){ + char *p=g_out; int n=0; + const char *pre="rect 0 0 120 40 "; while(*pre) p[n++]=*pre++; + n+=i2s(CB_COLOR, p+n); + p[n]=0; + return n; +} +#endif + +int cb_run(int in_len){ + int a = (in_len > 0) ? g_in[0] : 0; + g_out[0] = (char)(a * 2); /* identidade de demonstracao */ + return 1; +} diff --git a/src/catblocks/plugins/compilers/c_plugin.c b/src/catblocks/plugins/compilers/c_plugin.c new file mode 100644 index 0000000..b33d0cf --- /dev/null +++ b/src/catblocks/plugins/compilers/c_plugin.c @@ -0,0 +1,34 @@ +/* catblocks - plugin .wasm: IR -> C. ABI em catblocks/plugin.h. */ +#include "../compilers/plugin_common.h" +#include "../compilers/plugin_emit.h" + +char g_in[IN_CAP]; +char g_out[OUT_CAP]; +Node g_nodes[MAXN]; +int g_nnodes, g_nvars; + +int cb_abi(void){ return 1; } +int cb_in_addr(void){ return (int)(unsigned long)g_in; } +int cb_out_addr(void){ return (int)(unsigned long)g_out; } + +static void scan_vars(int idx){ + for(;idx>=0;idx=g_nodes[idx].next){ + Node*n=&g_nodes[idx]; + if((n->op==17||n->op==16) && n->v0+1>g_nvars) g_nvars=n->v0+1; + if(n->op==21 && n->v0+1>g_nvars) g_nvars=n->v0+1; + for(int i=0;inin;i++) scan_vars(n->c[i]); + scan_vars(n->body); scan_vars(n->alt); + } +} +int cb_run(int in_len){ + cbir_parse(g_in, in_len); + scan_vars(0); + oinit(); + oputs("/* gerado por catblocks IR->C (plugin wasm) */\n#include \n"); + oputs("static void cb_print(int v){ printf(\"%d\\n\", v); }\n"); + oputs("int main(void){\n"); + for(int i=0;i='0'&&c<='9'; } +static int parse_int(const char **pp){ const char *p=*pp; int sign=1,v=0; + if (*p=='-'){sign=-1;p++;} while(is_digit(*p)){v=v*10+(*p-'0');p++;} *pp=p; return v*sign; } +static void skip_ws(const char **pp){ const char *p=*pp; while(*p==' '||*p=='\t')p++; *pp=p; } + +/* Le o CBIR; devolve o numero de nos ou -1. */ +static int cbir_parse(const char *s, int len){ + const char *p=s, *e=s+len; g_nnodes=0; g_nvars=0; + /* saltar linhas de comentario/cabecalho */ + while (p=e) break; if (*p=='\n'){p++;continue;} + if (*p=='#'){ while(pop=parse_int(&p); skip_ws(&p); n->v0=parse_int(&p); skip_ws(&p); n->nin=parse_int(&p); + for(int i=0;i<4;i++){ skip_ws(&p); n->c[i]=parse_int(&p); } + skip_ws(&p); n->next=parse_int(&p); skip_ws(&p); n->body=parse_int(&p); skip_ws(&p); n->alt=parse_int(&p); + g_nnodes++; if(g_nnodes>=MAXN) break; + while(p0){ b[n++]='0'+v%10; v/=10; } for(int i=n-1;i>=0;i--){ char c[2]={b[i],0}; oputs(c);} } +static void spc(int k){ for(int i=0;i"; case 9:return "=="; + case 10:return "!="; case 11:return "<="; case 12:return ">="; case 13:return "&&"; + case 14:return "||"; default:return 0; } } + +static void ew(int idx); +static void ec(int idx); +static void lw(int idx, int k); +static void lc(int idx, int k); +static void sw(int idx, int k); +static void sc(int idx, int k); + +static void ew(int idx){ + if(idx<0||idx>=g_nnodes){ oputs("i32.const 0\n"); return; } + Node*n=&g_nodes[idx]; + if(n->op==1){ oputs("i32.const "); oputi(n->v0); oputs("\n"); } + else if(n->op==16){ oputs("local.get $v"); oputi(n->v0); oputs("\n"); } + else if(n->op==15){ ew(n->c[0]); oputs("i32.eqz\n"); } + else { const char*b=wat_binop(n->op); if(b){ ew(n->c[0]); ew(n->c[1]); oputs(b); oputs("\n"); } else oputs("i32.const 0\n"); } +} +static void ec(int idx){ + if(idx<0||idx>=g_nnodes){ oputs("0"); return; } + Node*n=&g_nodes[idx]; + if(n->op==1){ oputi(n->v0); } + else if(n->op==16){ oputs("v"); oputi(n->v0); } + else if(n->op==15){ oputs("!("); ec(n->c[0]); oputs(")"); } + else { const char*b=c_binop(n->op); if(b){ oputs("("); ec(n->c[0]); oputs(b); ec(n->c[1]); oputs(")"); } else oputs("0"); } +} + +static void lw(int idx, int k){ while(idx>=0){ sw(idx,k); idx=g_nodes[idx].next; } } +static void lc(int idx, int k){ while(idx>=0){ sc(idx,k); idx=g_nodes[idx].next; } } + +static void sw(int idx, int k){ + if(idx<0||idx>=g_nnodes) return; Node*n=&g_nodes[idx]; + if(n->op==17){ spc(k); ew(n->c[0]); oputs("local.set $v"); oputi(n->v0); oputs("\n"); } + else if(n->op==18){ spc(k); ew(n->c[0]); oputs("call $print\n"); } + else if(n->op==19){ + spc(k); oputs("(if "); ew(n->c[0]); oputs("(then\n"); lw(n->body,k+1); + spc(k); oputs(")"); + if(n->alt>=0){ oputs("(else\n"); lw(n->alt,k+1); spc(k); oputs(")"); } + oputs(")\n"); + } else if(n->op==20){ + spc(k); oputs("(block $ex\n"); spc(k+1); oputs("(loop $lp\n"); + spc(k+2); ew(n->c[0]); oputs("i32.eqz\n"); spc(k+2); oputs("br_if $ex\n"); + lw(n->body,k+2); spc(k+2); oputs("br $lp\n"); + spc(k+1); oputs(")\n"); spc(k); oputs(")\n"); + } else if(n->op==21){ + spc(k); ew(n->c[0]); oputs("local.set $v"); oputi(n->v0); oputs("\n"); + spc(k); oputs("(block $ex\n"); spc(k+1); oputs("(loop $lp\n"); + spc(k+2); oputs("local.get $v"); oputi(n->v0); oputs("\n"); ew(n->c[1]); oputs("i32.ge_s\n"); + spc(k+2); oputs("br_if $ex\n"); lw(n->body,k+2); + spc(k+2); oputs("local.get $v"); oputi(n->v0); oputs("\ni32.const 1\ni32.add\nlocal.set $v"); oputi(n->v0); oputs("\n"); + spc(k+2); oputs("br $lp\n"); spc(k+1); oputs(")\n"); spc(k); oputs(")\n"); + } +} +static void sc(int idx, int k){ + if(idx<0||idx>=g_nnodes) return; Node*n=&g_nodes[idx]; + if(n->op==17){ spc(k); oputs("v"); oputi(n->v0); oputs(" = "); ec(n->c[0]); oputs(";\n"); } + else if(n->op==18){ spc(k); oputs("cb_print("); ec(n->c[0]); oputs(");\n"); } + else if(n->op==19){ + spc(k); oputs("if ("); ec(n->c[0]); oputs(") {\n"); lc(n->body,k+1); spc(k); oputs("}"); + if(n->alt>=0){ oputs(" else {\n"); lc(n->alt,k+1); spc(k); oputs("}"); } + oputs("\n"); + } else if(n->op==20){ + spc(k); oputs("while ("); ec(n->c[0]); oputs(") {\n"); lc(n->body,k+1); spc(k); oputs("}\n"); + } else if(n->op==21){ + spc(k); oputs("for (v"); oputi(n->v0); oputs(" = "); ec(n->c[0]); + oputs("; v"); oputi(n->v0); oputs(" < "); ec(n->c[1]); + oputs("; v"); oputi(n->v0); oputs("++) {\n"); lc(n->body,k+1); spc(k); oputs("}\n"); + } +} +#endif diff --git a/src/catblocks/plugins/compilers/wasm_plugin.c b/src/catblocks/plugins/compilers/wasm_plugin.c new file mode 100644 index 0000000..43af12e --- /dev/null +++ b/src/catblocks/plugins/compilers/wasm_plugin.c @@ -0,0 +1,113 @@ +/* catblocks - plugin .wasm: IR -> wasm (binario MVP). Emite bytes diretamente. + * O modulo gerado importa "catblocks"."print" (func 0) e exporta "main" (func 1). */ +#include "../compilers/plugin_common.h" + +char g_in[IN_CAP]; +char g_out[OUT_CAP]; +static char g_body[OUT_CAP]; +Node g_nodes[MAXN]; +int g_nnodes, g_nvars; + +int cb_abi(void){ return 1; } +int cb_in_addr(void){ return (int)(unsigned long)g_in; } +int cb_out_addr(void){ return (int)(unsigned long)g_out; } + +static char *g_dst; static int g_dcnt; +static void w1(int b){ if(g_dcnt>=7; if(v) b|=0x80; w1(b); } while(v); } +static void ws(int v){ int more=1; while(more){ int b=v&0x7f; v>>=7; if((v==0&&!(b&0x40))||(v==-1&&(b&0x40))) more=0; else b|=0x80; w1(b);} } +static void wbytes(const char*s,int n){ for(int i=0;i=g_nnodes){ w1(0x41); ws(0); return; } + Node*n=&g_nodes[idx]; + if(n->op==1){ w1(0x41); ws(n->v0); } + else if(n->op==16){ w1(0x20); wu(n->v0); } + else if(n->op==15){ e_expr(n->c[0]); w1(0x45); } + else { int b=binop(n->op); if(b){ e_expr(n->c[0]); e_expr(n->c[1]); w1(b); } else { w1(0x41); ws(0); } } +} +static void e_list(int idx){ while(idx>=0){ e_stmt(idx); idx=g_nodes[idx].next; } } +static void e_stmt(int idx){ + if(idx<0||idx>=g_nnodes) return; Node*n=&g_nodes[idx]; + if(n->op==17){ e_expr(n->c[0]); w1(0x21); wu(n->v0); } + else if(n->op==18){ e_expr(n->c[0]); w1(0x10); wu(0); } + else if(n->op==19){ + e_expr(n->c[0]); w1(0x04); w1(0x40); e_list(n->body); + if(n->alt>=0){ w1(0x05); e_list(n->alt); } + w1(0x0b); + } else if(n->op==20){ + w1(0x02); w1(0x40); w1(0x03); w1(0x40); + e_expr(n->c[0]); w1(0x45); w1(0x0d); wu(1); + e_list(n->body); w1(0x0c); wu(0); + w1(0x0b); w1(0x0b); + } else if(n->op==21){ + e_expr(n->c[0]); w1(0x21); wu(n->v0); + w1(0x02); w1(0x40); w1(0x03); w1(0x40); + w1(0x20); wu(n->v0); e_expr(n->c[1]); w1(0x4e); w1(0x0d); wu(1); + e_list(n->body); + w1(0x20); wu(n->v0); w1(0x41); ws(1); w1(0x6a); w1(0x21); wu(n->v0); + w1(0x0c); wu(0); + w1(0x0b); w1(0x0b); + } +} + +static void scan_vars(int idx){ + for(;idx>=0;idx=g_nodes[idx].next){ + Node*n=&g_nodes[idx]; + if((n->op==17||n->op==16||n->op==21) && n->v0+1>g_nvars) g_nvars=n->v0+1; + for(int i=0;inin;i++) scan_vars(n->c[i]); + scan_vars(n->body); scan_vars(n->alt); + } +} + +/* a seccao e' emitida em g_sec e depois copiada com id+len para g_out */ +static char g_sec[OUT_CAP]; static int g_seclen; static int g_outlen; +static void sec_begin(void){ g_dst=g_sec; g_dcnt=0; } +static void sec_end(int id){ g_seclen=g_dcnt; g_dst=g_out; g_dcnt=g_outlen; w1(id); wu(g_seclen); wbytes(g_sec,g_seclen); g_outlen=g_dcnt; } + +int cb_run(int in_len){ + cbir_parse(g_in, in_len); + scan_vars(0); + /* corpo da funcao em g_body */ + g_dst=g_body; g_dcnt=0; + if(g_nvars==0) w1(0x00); + else { wu(g_nvars); for(int i=0;i() */ + w1(0x60); wu(0); wu(0); /* ()->() */ + sec_end(1); + sec_begin(); /* sec 2: import catblocks.print : (i32)->() */ + wu(1); + wu(9); wbytes("catblocks",9); + wu(5); wbytes("print",5); + w1(0); wu(0); + sec_end(2); + sec_begin(); /* sec 3: funcao main : ()->() */ + wu(1); wu(1); + sec_end(3); + sec_begin(); /* sec 7: export main */ + wu(1); wu(4); wbytes("main",4); w1(0); wu(1); + sec_end(7); + sec_begin(); /* sec 10: code */ + wu(1); wu(blen); wbytes(g_body,blen); + sec_end(10); + return g_dcnt; +} diff --git a/src/catblocks/plugins/compilers/wat_plugin.c b/src/catblocks/plugins/compilers/wat_plugin.c new file mode 100644 index 0000000..637b754 --- /dev/null +++ b/src/catblocks/plugins/compilers/wat_plugin.c @@ -0,0 +1,34 @@ +/* catblocks - plugin .wasm: IR -> WAT. ABI em catblocks/plugin.h. */ +#include "../compilers/plugin_common.h" +#include "../compilers/plugin_emit.h" + +char g_in[IN_CAP]; +char g_out[OUT_CAP]; +Node g_nodes[MAXN]; +int g_nnodes, g_nvars; + +int cb_abi(void){ return 1; } +int cb_in_addr(void){ return (int)(unsigned long)g_in; } +int cb_out_addr(void){ return (int)(unsigned long)g_out; } + +static void scan_vars(int idx){ + for(;idx>=0;idx=g_nodes[idx].next){ + Node*n=&g_nodes[idx]; + if((n->op==15||n->op==17||n->op==21)) { /* var get/set/for */ } + if((n->op==17||n->op==16) && n->v0+1>g_nvars) g_nvars=n->v0+1; + if(n->op==21 && n->v0+1>g_nvars) g_nvars=n->v0+1; + for(int i=0;inin;i++) scan_vars(n->c[i]); + scan_vars(n->body); scan_vars(n->alt); + } +} +int cb_run(int in_len){ + cbir_parse(g_in, in_len); + scan_vars(0); + oinit(); + oputs("(module\n (import \"catblocks\" \"print\" (func $print (param i32)))\n"); + oputs(" (func $main (export \"main\")\n"); + for(int i=0;i + +cb_node *cb_const(int32_t v) { return cb_node_new(CB_OP_CONST, v); } +static cb_node *b2(int op, cb_node *a, cb_node *b) { cb_node *n = cb_node_new(op,0); cb_node_add_in(n,a); cb_node_add_in(n,b); return n; } + +/* Programa 1: soma 1..n com "for", imprime o total e um "while" de contagem. + * vars: v0 = acumulador, v1 = i, v2 = contador do while. Devolve 5050+... */ +cb_node *cb_program_sum(void) { + /* v0 = 0; for v1 in 1..101 { v0 = v0 + v1 } -> 5050 */ + cb_node *init = cb_node_new(CB_OP_VAR_SET, 0); + cb_node_add_in(init, cb_const(0)); + cb_node *badd = b2(CB_OP_ADD, cb_node_new(CB_OP_VAR_GET,0), cb_node_new(CB_OP_VAR_GET,1)); + cb_node *aset = cb_node_new(CB_OP_VAR_SET, 0); cb_node_add_in(aset, badd); + cb_node *f = cb_node_new(CB_OP_FOR, 1); + cb_node_add_in(f, cb_const(1)); cb_node_add_in(f, cb_const(101)); + f->body = aset; + cb_node *pr = cb_node_new(CB_OP_PRINT, 0); cb_node_add_in(pr, cb_node_new(CB_OP_VAR_GET,0)); + init->next = f; f->next = pr; + return init; +} diff --git a/src/catblocks/wasm.c b/src/catblocks/wasm.c new file mode 100644 index 0000000..5fd9b2c --- /dev/null +++ b/src/catblocks/wasm.c @@ -0,0 +1,545 @@ +/* catblocks - interpretador WebAssembly (MVP + sign-ext) host-side, sem JIT. + * Implementa include/catblocks/wasm.h. + * Suporta: i32/i64 (e f32/f64 como bits) const/aritmetica/comparacao, locais, + * globais, load/store, call (incl. imports de host), block/loop/if/else/br/ + * br_if/br_table/return/end, controlo estruturado, segmentos de dados. */ +#include "catblocks/wasm.h" +#include +#include +#include + +#define MAXT 128 +#define MAXF 512 +#define MAXE 256 +#define MAXI 128 +#define MAXG 128 +#define MAXL 256 +#define MAXSEG 32 +#define MAXBLK 256 +#define MAXCTL 256 +#define STK 4096 + +typedef struct { int np, nr; uint8_t p[8], r[2]; } FType; + +typedef struct { + int tidx; + const uint8_t *body; /* apos a declaracao de locais */ + uint32_t blen; + int nparams, nlocals; /* nlocals = locais declarados (nao conta params) */ + uint8_t ptypes[8]; + uint8_t ltypes[MAXL]; + int nblk; + uint32_t bopen[MAXBLK], bend[MAXBLK], belse[MAXBLK]; /* pc do opcode -> match */ +} Func; + +typedef struct { char name[96]; uint8_t kind; int idx; } Exp; +typedef struct { uint32_t off; const uint8_t *data; uint32_t len; } Seg; +typedef struct { char mod[48]; char name[48]; uint8_t kind; int typeidx; } Imp; + +struct wasm_module { + FType types[MAXT]; int ntypes; + Imp imps[MAXI]; int nimp; int nimpfunc; + Func funcs[MAXF]; int nfuncs; /* apenas funcoes definidas */ + Exp exps[MAXE]; int nexps; + uint8_t gt[MAXG]; uint64_t ginit[MAXG]; int nglob; int gmut[MAXG]; + uint32_t memmin; int has_mem; int start; + Seg segs[MAXSEG]; int nsegs; + uint8_t *raw; size_t rawlen; /* copia dos bytes (para code/data) */ +}; + +struct wasm_inst { + wasm_module *m; + const wasm_import_def *imps; int nimps; + void *user; + uint8_t *mem; uint32_t pages, maxpages; + uint64_t glob[MAXG]; + char err[200]; +}; + +static int wasm_call_func(wasm_inst *in, int fidx, const wval *args, int nargs, wval *ret); +static int wasm_call_func_inner(wasm_inst *in, int fidx, const wval *args, int nargs, wval *ret); + +/* ---------- LEB (avancam *pp) ---------- */ +static uint32_t uleb(const uint8_t **pp, const uint8_t *e) { + const uint8_t *p = *pp; uint32_t v = 0; int s = 0; uint8_t b = 0; + do { if (p >= e) break; b = *p++; v |= (uint32_t)(b & 0x7f) << s; s += 7; } while (b & 0x80); + *pp = p; return v; +} +static int64_t sleb(const uint8_t **pp, const uint8_t *e, int bits) { + const uint8_t *p = *pp; uint64_t v = 0; int s = 0; uint8_t b = 0; + do { if (p >= e) break; b = *p++; v |= (uint64_t)(b & 0x7f) << s; s += 7; } while (b & 0x80); + if (s < bits && (b & 0x40)) v |= ~(uint64_t)0 << s; + *pp = p; + if (bits == 32) return (int64_t)(int32_t)(uint32_t)v; + return (int64_t)v; +} + +/* ---------- varredura de blocos: pre-calcula pareamento opcode<->end ---------- + * Percorre o corpo linearmente. Para cada opcode estrutural (block/loop/if) + * empilha o pc do opcode; para cada 'end' (0x0b) liga. 'else' (0x05) liga ao if. */ +static void skip_imm(uint8_t op, const uint8_t **pp, const uint8_t *e) { + switch (op) { + case 0x02: case 0x03: case 0x04: uleb(pp, e); break; /* block/loop/if (blocktype) */ + case 0x0c: case 0x0d: uleb(pp, e); break; /* br / br_if */ + case 0x0e: { uint32_t n = uleb(pp, e); for (uint32_t i = 0; i < n; i++) uleb(pp, e); uleb(pp, e); } break; /* br_table */ + case 0x10: uleb(pp, e); break; /* call */ + case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: uleb(pp, e); break; /* local/global get/set */ + case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: + case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: + case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: + case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: uleb(pp, e); uleb(pp, e); break; /* loads/stores */ + case 0x3f: case 0x40: (*pp)++; break; /* memory.size/grow */ + case 0x41: sleb(pp, e, 32); break; /* i32.const */ + case 0x42: sleb(pp, e, 64); break; /* i64.const */ + case 0x43: *pp += 4; break; /* f32.const */ + case 0x44: *pp += 8; break; /* f64.const */ + default: break; + } +} + +/* ---------- helpers de leitura de secao ---------- */ +static int rd_section(const uint8_t **pp, const uint8_t *e, uint32_t *id, const uint8_t **body, const uint8_t **bend) { + const uint8_t *p = *pp; + if (p >= e) return 0; + *id = *p++; + uint32_t n = uleb(&p, e); + if (p + n > e) return 0; + *body = p; *bend = p + n; *pp = p + n; return 1; +} + +/* le uma funcao: corpos (10) */ +static void scan_body(Func *fn) { + fn->nblk = 0; + const uint8_t *p = fn->body, *e = fn->body + fn->blen; + uint32_t stack[MAXBLK]; int sp = 0; + while (p < e) { + uint32_t pc = (uint32_t)(p - fn->body); + uint8_t op = *p++; + if (op == 0x02 || op == 0x03 || op == 0x04) { + if (sp < MAXBLK && fn->nblk < MAXBLK) { + fn->bopen[fn->nblk] = pc; fn->belse[fn->nblk] = 0; + stack[sp++] = fn->nblk; fn->nblk++; + } + skip_imm(op, &p, e); + } else if (op == 0x05) { /* else */ + if (sp) fn->belse[stack[sp-1]] = pc; + } else if (op == 0x0b) { /* end */ + if (sp) { int bi = stack[--sp]; fn->bend[bi] = pc; } + } else { + skip_imm(op, &p, e); + } + } +} + +static int find_blk(const Func *fn, uint32_t pc) { + for (int i = 0; i < fn->nblk; i++) if (fn->bopen[i] == pc) return i; + return -1; +} + +/* ---------- carga do modulo ---------- */ +wasm_module *wasm_load(const uint8_t *bytes, size_t len, char *err, size_t errcap) { + wasm_module *m = (wasm_module*)calloc(1, sizeof(wasm_module)); + if (!m) { snprintf(err, errcap, "oom"); return NULL; } + m->raw = (uint8_t*)malloc(len); if (!m->raw) { free(m); snprintf(err,errcap,"oom"); return NULL; } + memcpy(m->raw, bytes, len); m->rawlen = len; + const uint8_t *p = m->raw, *e = m->raw + len; + if (len < 8 || memcmp(p, "\0asm\x01\0\0\0", 8) != 0) { snprintf(err,errcap,"bad magic"); goto fail; } + p += 8; + while (p < e) { + uint32_t id; const uint8_t *b, *be; + if (!rd_section(&p, e, &id, &b, &be)) { snprintf(err,errcap,"bad section"); goto fail; } + const uint8_t *q = b; + switch (id) { + case 1: { /* types */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXT; i++) { + if (q < be && *q++ != 0x60) { snprintf(err,errcap,"type form"); goto fail; } + uint32_t np = uleb(&q, be); FType *t = &m->types[m->ntypes]; + t->np = (int)np; t->nr = 0; + for (uint32_t j = 0; j < np && j < 8; j++) t->p[j] = *q++; + uint32_t nr = uleb(&q, be); + t->nr = (int)nr; + for (uint32_t j = 0; j < nr && j < 2; j++) t->r[j] = *q++; + m->ntypes++; + } + } break; + case 2: { /* imports */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXI; i++) { + uint32_t ml = uleb(&q, be); Imp *im = &m->imps[m->nimp]; + uint32_t c = ml < 47 ? ml : 47; memcpy(im->mod, q, c); im->mod[c]=0; q += ml; + uint32_t nl = uleb(&q, be); c = nl < 47 ? nl : 47; memcpy(im->name, q, c); im->name[c]=0; q += nl; + im->kind = *q++; + if (im->kind == 0) { im->typeidx = (int)uleb(&q, be); m->nimpfunc++; } + else if (im->kind == 2) { uleb(&q, be); if (q < be && *q++ == 1) uleb(&q, be); } + else if (im->kind == 3) { *q++; *q++; } + m->nimp++; + } + } break; + case 3: { /* functions */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXF; i++) { m->funcs[m->nfuncs].tidx = (int)uleb(&q, be); m->nfuncs++; } + } break; + case 5: { /* memory */ + uint32_t n = uleb(&q, be); + if (n) { m->has_mem = 1; if (*q++ == 0) { m->memmin = uleb(&q, be); } } + } break; + case 6: { /* globals */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXG; i++) { + m->gt[m->nglob] = *q++; m->gmut[m->nglob] = *q++; + if (*q == 0x41) { q++; m->ginit[m->nglob] = (uint64_t)(uint32_t)sleb(&q, be, 32); } + else if (*q == 0x42) { q++; m->ginit[m->nglob] = (uint64_t)sleb(&q, be, 64); } + else if (*q == 0x43) { q++; uint32_t u; memcpy(&u, q, 4); q += 4; m->ginit[m->nglob] = u; } + else if (*q == 0x44) { q++; memcpy(&m->ginit[m->nglob], q, 8); q += 8; } + if (q < be && *q == 0x0b) q++; + m->nglob++; + } + } break; + case 7: { /* exports */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXE; i++) { + uint32_t nl = uleb(&q, be); Exp *ex = &m->exps[m->nexps]; + uint32_t c = nl < 95 ? nl : 95; memcpy(ex->name, q, c); ex->name[c]=0; q += nl; + ex->kind = *q++; ex->idx = (int)uleb(&q, be); m->nexps++; + } + } break; + case 8: m->start = (int)uleb(&q, be); break; + case 10: { /* code */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXF; i++) { + uint32_t sz = uleb(&q, be); const uint8_t *cb = q; const uint8_t *ce = q + sz; + Func *fn = &m->funcs[i]; + uint32_t nl = uleb(&q, ce); fn->nlocals = 0; + for (uint32_t j = 0; j < nl; j++) { uint32_t cnt = uleb(&q, ce); uint8_t ty = *q++; + for (uint32_t k = 0; k < cnt && fn->nlocals < MAXL; k++) fn->ltypes[fn->nlocals++] = ty; } + fn->body = q; fn->blen = (uint32_t)(ce - q); + scan_body(fn); + q = ce; + (void)cb; + } + } break; + case 11: { /* data */ + uint32_t n = uleb(&q, be); + for (uint32_t i = 0; i < n && i < MAXSEG; i++) { + uint32_t flags = uleb(&q, be); Seg *s = &m->segs[m->nsegs]; + if (flags == 0) { if (*q++ == 0x41) { s->off = uleb(&q, be); } if (qoff = 0; } + uint32_t dl = uleb(&q, be); s->data = q; s->len = dl; q += dl; m->nsegs++; + } + } break; + default: break; + } + } + return m; +fail: + wasm_module_free(m); return NULL; +} + +void wasm_module_free(wasm_module *m) { + if (!m) return; + free(m->raw); free(m); +} + +int wasm_export_sig(const wasm_module *m, const char *name, int kind, wasm_sig *sig) { + int idx = -1; + for (int i = 0; i < m->nexps; i++) { + if (m->exps[i].kind == (uint8_t)kind && strcmp(m->exps[i].name, name) == 0) { idx = m->exps[i].idx; break; } + } + if (idx < 0) return 0; + if (kind != WK_FUNC) return 1; + int ti = -1; /* func idx -> type, considere imports primeiro */ + if (idx < m->nimpfunc) { + int f = 0; + for (int i = 0; i < m->nimp; i++) if (m->imps[i].kind == 0) { if (f == idx) { ti = m->imps[i].typeidx; break; } f++; } + } else { + int di = idx - m->nimpfunc; + if (di < m->nfuncs) ti = m->funcs[di].tidx; + } + if (ti < 0 || ti >= m->ntypes) return 0; + if (sig) { sig->np = m->types[ti].np; sig->nr = m->types[ti].nr; + memcpy(sig->p, m->types[ti].p, 8); memcpy(sig->r, m->types[ti].r, 2); } + return 1; +} + +int wasm_import_count(const wasm_module *m) { return m->nimp; } +void wasm_import_name(const wasm_module *m, int i, const char **mod, const char **name) { + if (i < 0 || i >= m->nimp) { *mod = *name = ""; return; } + *mod = m->imps[i].mod; *name = m->imps[i].name; +} + +/* ---------- instanciacao ---------- */ +wasm_inst *wasm_instantiate(wasm_module *m, const wasm_import_def *imps, int nimps, + uint32_t max_mem_pages, char *err, size_t errcap) { + wasm_inst *in = (wasm_inst*)calloc(1, sizeof(wasm_inst)); + if (!in) { snprintf(err,errcap,"oom"); return NULL; } + in->m = m; in->imps = imps; in->nimps = nimps; + uint32_t initpages = m->has_mem ? m->memmin : 0; + uint32_t cap = max_mem_pages ? max_mem_pages : 256; + in->pages = initpages; in->maxpages = cap; + if (m->has_mem || in->pages == 0) { + in->mem = (uint8_t*)calloc((size_t)(in->pages ? in->pages : 1) * 65536u, 1); + if (!in->mem) { free(in); snprintf(err,errcap,"oom mem"); return NULL; } + } + for (int i = 0; i < m->nglob; i++) in->glob[i] = m->ginit[i]; + for (int i = 0; i < m->nsegs; i++) { + if (m->segs[i].off + m->segs[i].len <= (uint64_t)in->pages * 65536u) + memcpy(in->mem + m->segs[i].off, m->segs[i].data, m->segs[i].len); + } + if (m->start) { + wval r; + int f = 0; for (int i = 0; i < m->nimp; i++) if (m->imps[i].kind == 0) f++; + int di = m->start - f; + if (di >= 0 && di < m->nfuncs) { + wasm_call_func(in, m->start, NULL, 0, &r); + } + } + return in; +} +void wasm_free(wasm_inst *in) { if (!in) return; free(in->mem); free(in); } +void *wasm_user(wasm_inst *in) { return in->user; } +void wasm_set_user(wasm_inst *in, void *u) { in->user = u; } +uint8_t *wasm_memory(wasm_inst *in, uint32_t *size) { if (size) *size = in->pages * 65536u; return in->mem; } +const char *wasm_error(wasm_inst *in) { return in->err; } + +/* ---------- executor ---------- */ +typedef struct { int kind; uint32_t start_pc, end_pc, else_pc, sp; } CFrame; /* kind:0 block 1 loop 2 if 3 func */ + +static uint32_t rd32(const uint8_t *p) { uint32_t v; memcpy(&v,p,4); return v; } +static uint64_t rd64(const uint8_t *p) { uint64_t v; memcpy(&v,p,8); return v; } +static void wr32(uint8_t *p, uint32_t v){ memcpy(p,&v,4); } +static void wr64(uint8_t *p, uint64_t v){ memcpy(p,&v,8); } + +static int wasm_call_func(wasm_inst *in, int fidx, const wval *args, int nargs, wval *ret) { + static int depth; + if (depth > 64) { snprintf(in->err, sizeof(in->err), "recursion too deep at fidx=%d (nimpfunc=%d nfuncs=%d)", fidx, in->m->nimpfunc, in->m->nfuncs); return 1; } + depth++; + int rc = wasm_call_func_inner(in, fidx, args, nargs, ret); + depth--; + return rc; +} +static int wasm_call_func_inner(wasm_inst *in, int fidx, const wval *args, int nargs, wval *ret) { + wasm_module *m = in->m; + int f = 0; int impidx = -1; + for (int i = 0; i < m->nimp; i++) if (m->imps[i].kind == 0) { if (f == fidx) { impidx = i; break; } f++; } + if (impidx >= 0) { + wasm_hostfn hf = NULL; void *ud = NULL; + for (int i = 0; i < in->nimps; i++) + if (strcmp(in->imps[i].mod, m->imps[impidx].mod) == 0 && + strcmp(in->imps[i].name, m->imps[impidx].name) == 0) { hf = in->imps[i].fn; ud = in->imps[i].ud; break; } + if (!hf) { snprintf(in->err, sizeof(in->err), "missing host import %s.%s", m->imps[impidx].mod, m->imps[impidx].name); return 1; } + return hf(in, args, ret, ud); + } + int di = fidx - f; + if (di < 0 || di >= m->nfuncs) { snprintf(in->err,sizeof(in->err),"bad func idx %d",fidx); return 1; } + Func *fn = &m->funcs[di]; + int ti = fn->tidx; + int np = (ti >= 0 && ti < m->ntypes) ? m->types[ti].np : 0; + int nl = np + fn->nlocals; + wval loc[512]; + if (nl > 512) nl = 512; + for (int i = 0; i < np && i < nargs; i++) loc[i] = args[i]; + for (int i = np; i < nl; i++) loc[i] = 0; + + const uint8_t *code = fn->body; const uint8_t *end = fn->body + fn->blen; + const uint8_t *p = code; + const char *trace = getenv("CB_WASM_TRACE"); + long steps = 0, limit = 20000000; + wval stk[STK]; int sp = 0; + CFrame cf[MAXCTL]; int cp = 0; + cf[cp].kind = 3; cf[cp].start_pc = 0; cf[cp].end_pc = fn->blen; cf[cp].sp = 0; cp++; + wval res = 0; int retflag = 0; +#define PUSH(x) do { if (sp < STK) stk[sp++] = (x); } while (0) +#define POP() (sp > 0 ? stk[--sp] : 0) + while (p < end) { + uint32_t pc = (uint32_t)(p - code); + uint8_t op = *p++; + if (trace) fprintf(stderr, "[f%d pc=%u op=0x%02x sp=%d cp=%d L0=%d L1=%d]", di, pc, op, sp, cp, (int)(int32_t)loc[0], (int)(int32_t)loc[1]); + if (trace && op == 0x10) { const uint8_t *tp = p; uint32_t tfi = uleb(&tp, end); fprintf(stderr, " call -> func %u\n", tfi); } + if (++steps > limit) { snprintf(in->err,sizeof(in->err),"step limit f%d pc=%u op=0x%02x",di,pc,op); return 1; } + switch (op) { + case 0x00: snprintf(in->err,sizeof(in->err),"unreachable"); return 1; + case 0x01: break; /* nop */ + case 0x02: { /* block */ + uint32_t bt = uleb(&p, end); (void)bt; int bi = find_blk(fn, pc); + cf[cp].kind = 0; cf[cp].start_pc = (uint32_t)(p - code); + cf[cp].end_pc = (bi >= 0 ? fn->bend[bi] : fn->blen); cf[cp].else_pc = 0; cf[cp].sp = sp; cp++; + } break; + case 0x03: { /* loop */ + uint32_t bt = uleb(&p, end); (void)bt; int bi = find_blk(fn, pc); + cf[cp].kind = 1; cf[cp].start_pc = (uint32_t)(p - code); + cf[cp].end_pc = (bi >= 0 ? fn->bend[bi] : fn->blen); cf[cp].else_pc = 0; cf[cp].sp = sp; cp++; + } break; + case 0x04: { /* if */ + uint32_t bt = uleb(&p, end); (void)bt; int bi = find_blk(fn, pc); + int32_t c = (int32_t)POP(); + uint32_t endpc = (bi >= 0 ? fn->bend[bi] : fn->blen); + uint32_t elsepc = (bi >= 0 ? fn->belse[bi] : 0); + if (c) { + cf[cp].kind = 2; cf[cp].start_pc = (uint32_t)(p - code); + cf[cp].end_pc = endpc; cf[cp].else_pc = elsepc; cf[cp].sp = sp; cp++; + } else if (elsepc) { + p = code + elsepc + 1; + cf[cp].kind = 2; cf[cp].start_pc = (uint32_t)(p - code); + cf[cp].end_pc = endpc; cf[cp].else_pc = elsepc; cf[cp].sp = sp; cp++; + } else { + p = code + endpc + 1; /* sem else: salta o corpo do if e o seu end */ + } + } break; + case 0x05: { /* else atingido apos o ramo "then": salta para o end */ + for (int i = cp-1; i >= 1; i--) if (cf[i].kind == 2) { + sp = cf[i].sp; p = code + cf[i].end_pc + 1; cp = i; break; } + } break; + case 0x0b: { /* end */ + if (cp > 1) { cp--; sp = cf[cp].sp; } else { p = end; } + } break; + case 0x0c: { /* br */ + uint32_t d = uleb(&p, end); int tgt = cp - 1 - (int)d; if (tgt < 0) tgt = 0; + sp = cf[tgt].sp; + if (cf[tgt].kind == 1) { p = code + cf[tgt].start_pc; cp = tgt + 1; } + else if (cf[tgt].kind == 3) { retflag = 1; } + else { p = code + cf[tgt].end_pc + 1; cp = tgt; } + } break; + case 0x0d: { /* br_if */ + uint32_t d = uleb(&p, end); int32_t c = (int32_t)POP(); + if (c) { + int tgt = cp - 1 - (int)d; if (tgt < 0) tgt = 0; + sp = cf[tgt].sp; + if (cf[tgt].kind == 1) { p = code + cf[tgt].start_pc; cp = tgt + 1; } + else if (cf[tgt].kind == 3) { retflag = 1; } + else { p = code + cf[tgt].end_pc + 1; cp = tgt; } + } + } break; + case 0x0e: { /* br_table */ + uint32_t cnt = uleb(&p, end); + uint32_t targets[256]; + for (uint32_t i = 0; i < cnt && i < 256; i++) targets[i] = uleb(&p, end); + uint32_t def = uleb(&p, end); + int32_t iv = (int32_t)POP(); + uint32_t d = (iv >= 0 && (uint32_t)iv < cnt) ? targets[iv] : def; + int tgt = cp - 1 - (int)d; if (tgt < 0) tgt = 0; + sp = cf[tgt].sp; + if (cf[tgt].kind == 1) { p = code + cf[tgt].start_pc; cp = tgt + 1; } + else if (cf[tgt].kind == 3) { retflag = 1; } + else { p = code + cf[tgt].end_pc + 1; cp = tgt; } + } break; + case 0x0f: retflag = 1; break; /* return */ + case 0x1a: (void)POP(); break; /* drop */ + case 0x1b: { /* select */ + int32_t c = (int32_t)POP(); wval v2 = POP(); wval v1 = POP(); + PUSH(c ? v1 : v2); + } break; + case 0x10: { /* call */ + uint32_t fi = uleb(&p, end); + int ti2 = -1, f2 = 0; + if ((int)fi < m->nimpfunc) { for (int i=0;inimp;i++) if (m->imps[i].kind==0) { if (f2==(int)fi) { ti2=m->imps[i].typeidx; break; } f2++; } } + else { int d2=(int)fi - m->nimpfunc; if (d2>=0 && d2nfuncs) ti2=m->funcs[d2].tidx; } + int na = (ti2>=0 && ti2ntypes) ? m->types[ti2].np : 0; + wval a[16]; if (na > 16) na = 16; + for (int i = na-1; i >= 0; i--) a[i] = POP(); + wval r2 = 0; + if (wasm_call_func(in, (int)fi, a, na, &r2)) return 1; + int nr = (ti2>=0 && ti2ntypes) ? m->types[ti2].nr : 0; + if (nr) PUSH(r2); + } break; + case 0x20: { uint32_t i = uleb(&p,end); PUSH(i < 512 ? loc[i] : 0); } break; /* local.get */ + case 0x21: { uint32_t i = uleb(&p,end); wval v = POP(); if (i < 512) loc[i] = v; } break; /* local.set */ + case 0x22: { uint32_t i = uleb(&p,end); wval v = POP(); if (i < 512) loc[i] = v; PUSH(v); } break; /* local.tee */ + case 0x23: { uint32_t i = uleb(&p,end); PUSH(i < MAXG ? in->glob[i] : 0); } break; /* global.get */ + case 0x24: { uint32_t i = uleb(&p,end); wval v = POP(); if (i < MAXG) in->glob[i] = v; } break; /* global.set */ + case 0x28: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+4)<=in->pages*65536u) PUSH(rd32(in->mem+a)); else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x29: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+8)<=in->pages*65536u) PUSH(rd64(in->mem+a)); else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x2b: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+1)<=in->pages*65536u) PUSH(in->mem[a]); else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x2c: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+1)<=in->pages*65536u) PUSH((int32_t)(int8_t)in->mem[a] & 0xffffffffu); else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x2d: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+2)<=in->pages*65536u) { uint16_t u; memcpy(&u,in->mem+a,2); PUSH((int32_t)(int16_t)u); } else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x30: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+1)<=in->pages*65536u) PUSH((int32_t)(int8_t)in->mem[a]); else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x31: { uleb(&p,end); uint32_t o=uleb(&p,end); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+2)<=in->pages*65536u) { uint16_t u; memcpy(&u,in->mem+a,2); PUSH((int32_t)(int16_t)u); } else { snprintf(in->err,sizeof(in->err),"oob load"); return 1; } } break; + case 0x36: { uleb(&p,end); uint32_t o=uleb(&p,end); wval v=POP(); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+4)<=in->pages*65536u) wr32(in->mem+a,(uint32_t)v); else { snprintf(in->err,sizeof(in->err),"oob store"); return 1; } } break; + case 0x37: { uleb(&p,end); uint32_t o=uleb(&p,end); wval v=POP(); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+8)<=in->pages*65536u) wr64(in->mem+a,v); else { snprintf(in->err,sizeof(in->err),"oob store"); return 1; } } break; + case 0x3a: { uleb(&p,end); uint32_t o=uleb(&p,end); wval v=POP(); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+1)<=in->pages*65536u) in->mem[a]=(uint8_t)v; else { snprintf(in->err,sizeof(in->err),"oob store"); return 1; } } break; + case 0x3b: { uleb(&p,end); uint32_t o=uleb(&p,end); wval v=POP(); int32_t a=(int32_t)POP()+o; if ((uint32_t)(a+2)<=in->pages*65536u) { uint16_t u=(uint16_t)v; memcpy(in->mem+a,&u,2); } else { snprintf(in->err,sizeof(in->err),"oob store"); return 1; } } break; + case 0x3f: { *p; uint8_t x=*p++; (void)x; PUSH(in->pages); } break; /* memory.size */ + case 0x40: { *p; uint8_t x=*p++; (void)x; uint32_t d=(uint32_t)POP(); if (in->pages + d <= in->maxpages) { PUSH((int32_t)in->pages); in->pages += d; } else PUSH(-1); } break; /* memory.grow */ + case 0x41: { int64_t v=sleb(&p,end,32); PUSH((uint32_t)v); } break; + case 0x42: { int64_t v=sleb(&p,end,64); PUSH((uint64_t)v); } break; + case 0x43: { uint32_t u; memcpy(&u,p,4); p+=4; PUSH(u); } break; + case 0x44: { uint64_t u; memcpy(&u,p,8); p+=8; PUSH(u); } break; + case 0x45: { int32_t a=(int32_t)POP(); PUSH(a==0); } break; + case 0x46: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a==b); } break; + case 0x47: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a!=b); } break; + case 0x48: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(ab); } break; + case 0x4b: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a>b); } break; + case 0x4c: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a<=b); } break; + case 0x4d: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a<=b); } break; + case 0x4e: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a>=b); } break; + case 0x4f: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(a>=b); } break; + case 0x50: { int64_t a=(int64_t)POP(); PUSH(a==0); } break; + case 0x51: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(a==b); } break; + case 0x52: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(a!=b); } break; + case 0x53: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(ab); } break; + case 0x57: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(a<=b); } break; + case 0x59: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(a>=b); } break; + case 0x67: { int32_t a=(int32_t)POP(); PUSH(__builtin_clz((uint32_t)a)); } break; + case 0x68: { int32_t a=(int32_t)POP(); PUSH(__builtin_ctz((uint32_t)a)); } break; + case 0x69: { int32_t a=(int32_t)POP(); PUSH(__builtin_popcount((uint32_t)a)); } break; + case 0x6a: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a+b)); } break; + case 0x6b: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a-b)); } break; + case 0x6c: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a*b)); } break; + case 0x6d: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(b?(uint32_t)(a/b):0); } break; + case 0x6e: { uint32_t b=(uint32_t)POP(),a=(uint32_t)POP(); PUSH(b?(a/b):0); } break; + case 0x6f: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH(b?(uint32_t)(a%b):0); } break; + case 0x70: { uint32_t b=(uint32_t)POP(),a=(uint32_t)POP(); PUSH(b?(a%b):0); } break; + case 0x71: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a&b)); } break; + case 0x72: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a|b)); } break; + case 0x73: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a^b)); } break; + case 0x74: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a<<(b & 31))); } break; + case 0x75: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)(a>>(b & 31))); } break; + case 0x76: { uint32_t b=(uint32_t)POP(),a=(uint32_t)POP(); PUSH(a>>(b & 31)); } break; + case 0x77: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)((uint32_t)a>>(b & 31))); } break; /* rotl */ + case 0x78: { int32_t b=(int32_t)POP(),a=(int32_t)POP(); PUSH((uint32_t)((uint32_t)a<<(b & 31))); } break; /* rotr approx */ + case 0x79: { int64_t a=(int64_t)POP(); PUSH(__builtin_clzll((uint64_t)a)); } break; + case 0x7a: { int64_t a=(int64_t)POP(); PUSH(__builtin_ctzll((uint64_t)a)); } break; + case 0x7b: { int64_t a=(int64_t)POP(); PUSH(__builtin_popcountll((uint64_t)a)); } break; + case 0x7c: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a+b)); } break; + case 0x7d: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a-b)); } break; + case 0x7e: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a*b)); } break; + case 0x7f: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(b?(uint64_t)(a/b):0); } break; + case 0x80: { uint64_t b=(uint64_t)POP(),a=(uint64_t)POP(); PUSH(b?(a/b):0); } break; + case 0x81: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH(b?(uint64_t)(a%b):0); } break; + case 0x82: { uint64_t b=(uint64_t)POP(),a=(uint64_t)POP(); PUSH(b?(a%b):0); } break; + case 0x83: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a&b)); } break; + case 0x84: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a|b)); } break; + case 0x85: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a^b)); } break; + case 0x86: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a<<(b & 63))); } break; + case 0x87: { int64_t b=(int64_t)POP(),a=(int64_t)POP(); PUSH((uint64_t)(a>>(b & 63))); } break; + case 0x88: { uint64_t b=(uint64_t)POP(),a=(uint64_t)POP(); PUSH(a>>(b & 63)); } break; + case 0xa7: { int64_t a=(int64_t)POP(); PUSH((uint32_t)(int32_t)a); } break; + case 0xac: { int32_t a=(int32_t)POP(); PUSH((uint64_t)(int64_t)a); } break; + case 0xad: { uint32_t a=(uint32_t)POP(); PUSH((uint64_t)a); } break; + case 0xbc: { uint32_t a=(uint32_t)POP(); PUSH(a); } break; + case 0xbd: { uint64_t a=(uint64_t)POP(); PUSH(a); } break; + case 0xbe: { uint32_t a=(uint32_t)POP(); PUSH(a); } break; + case 0xbf: { uint64_t a=(uint64_t)POP(); PUSH(a); } break; + + default: snprintf(in->err,sizeof(in->err),"unimpl opcode 0x%02x",op); return 1; + } + if (retflag) break; + } + if (sp > 0) res = stk[sp-1]; + if (ret) *ret = res; + return 0; +#undef PUSH +#undef POP +} +int wasm_call(wasm_inst *in, const char *export_name, const wval *args, int nargs, wval *ret) { + wasm_module *m = in->m; + for (int i = 0; i < m->nexps; i++) { + if (m->exps[i].kind == WK_FUNC && strcmp(m->exps[i].name, export_name) == 0) + return wasm_call_func(in, m->exps[i].idx, args, nargs, ret); + } + snprintf(in->err, sizeof(in->err), "export '%s' not found", export_name); + return 1; +} diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..2a3838d --- /dev/null +++ b/src/main.c @@ -0,0 +1,116 @@ +/* catblocks - CLI principal. + * catblocks run interpreta o programa de exemplo + * catblocks wat emite .wat (plugin .wasm IR->WAT) + * catblocks c emite .c (plugin .wasm IR->C) + * catblocks wasm emite .wasm binario (plugin .wasm IR->WASM) + * catblocks ir imprime o IR serializado (CBIR) + * catblocks blocks lista os blocos .wasm e as interfaces + * catblocks help + */ +#include "catblocks/ir.h" +#include "catblocks/plugin.h" +#include "catblocks/programs.h" +#include +#include +#include + +extern char *cb_interp_run(cb_node *root, int nvars, char **out, size_t *outlen); + +#define PLUGIN_DIR "build/plugins" + +static int host_print(wasm_inst *in, const wval *args, wval *ret, void *ud) { + (void)in; (void)ret; + printf("%d\n", (int)(int32_t)args[0]); + if (ud) (*(int*)ud)++; + return 0; +} + +static int do_out(const char *plugin, const char *outfile) { + cb_node *root = cb_program_sum(); + cb_str ir; cb_str_init(&ir); cb_ir_serialize(root, &ir); + char path[256], err[256]; + snprintf(path, sizeof path, "%s/%s", PLUGIN_DIR, plugin); + cb_plugin *p = cb_plugin_load_file(path, err, sizeof err); + if (!p) { fprintf(stderr, "erro ao carregar plugin %s: %s\n", path, err); return 1; } + size_t n = 0; + char *o = cb_plugin_run(p, ir.buf, ir.len, &n); + if (!o) { fprintf(stderr, "erro no plugin %s: %s\n", plugin, cb_plugin_error(p)); cb_plugin_free(p); return 1; } + FILE *f = fopen(outfile, "wb"); + if (!f) { perror(outfile); return 1; } + fwrite(o, 1, n, f); fclose(f); + printf("escrito %s (%zu bytes)\n", outfile, n); + free(o); cb_plugin_free(p); cb_str_free(&ir); cb_node_free_all(NULL); + return 0; +} + +static int cmd_run(void) { + cb_node *root = cb_program_sum(); + char *out = NULL; size_t olen = 0; + cb_interp_run(root, 4, &out, &olen); + if (out) fputs(out, stdout); + free(out); cb_node_free_all(NULL); + return 0; +} + +static int cmd_ir(void) { + cb_node *root = cb_program_sum(); + cb_str s; cb_str_init(&s); cb_ir_serialize(root, &s); + fputs(s.buf, stdout); cb_str_free(&s); cb_node_free_all(NULL); + return 0; +} + +static int cmd_blocks(void) { + const char *b[] = {"add","subtract","multiply","divide","and","or","not", + "if","else","while","for","when_start"}; + printf("%-12s %-9s %-7s %-8s %s\n","bloco","BlockLike","Render","cor","nome"); + for (unsigned i = 0; i < sizeof(b)/sizeof(b[0]); i++) { + char path[256], err[256]; + snprintf(path, sizeof path, "%s/blocks/%s.wasm", PLUGIN_DIR, b[i]); + cb_plugin *p = cb_plugin_load_file(path, err, sizeof err); + if (!p) { printf("%-12s (nao carregou)\n", b[i]); continue; } + int col = cb_plugin_export_i32(p, "block_color", 0); + int nl = cb_plugin_export_i32(p, "block_name", 0); + char name[64] = "?"; + if (nl > 0 && nl < 63) { int oa; uint32_t ms; char *m = cb_plugin_outbuf(p, &oa, &ms); + if (m && oa + nl <= (int)ms) { memcpy(name, m+oa, nl); name[nl]=0; } } + printf("%-12s %-9d %-7d 0x%06X %s\n", b[i], cb_plugin_has_blocklike(p), + cb_plugin_has_renderable(p), col, name); + cb_plugin_free(p); + } + return 0; +} + +static int cmd_exec_wasm(const char *file) { + char err[256]; + cb_plugin *p = cb_plugin_load_file(file, err, sizeof err); + if (!p) { fprintf(stderr, "erro: %s\n", err); return 1; } + int h = 0; + (void)h; + cb_plugin_free(p); + fprintf(stderr, "uso interno: ver tests/ para execucao do .wasm gerado\n"); + return 0; +} + +int main(int argc, char **argv) { + if (argc < 2) { fprintf(stderr, "uso: %s {run|wat|c|wasm|ir|blocks|help}\n", argv[0]); return 2; } + const char *c = argv[1]; + if (!strcmp(c,"run")) return cmd_run(); + if (!strcmp(c,"ir")) return cmd_ir(); + if (!strcmp(c,"blocks")) return cmd_blocks(); + if (!strcmp(c,"wat")) return do_out("compiler_wat.wasm", "build/catblocks_out.wat"); + if (!strcmp(c,"c")) return do_out("compiler_c.wasm", "build/catblocks_out.c"); + if (!strcmp(c,"wasm")) return do_out("compiler_wasm.wasm", "build/catblocks_out.wasm"); + if (!strcmp(c,"exec-wasm")) return cmd_exec_wasm(argc>2?argv[2]:""); + if (!strcmp(c,"help")) { + printf("catblocks: linguagem visual baseada em nos, tudo plugin .wasm\n"); + printf(" run interpreta o grafo de exemplo\n"); + printf(" ir imprime o CBIR\n"); + printf(" wat compila IR->.wat (plugin .wasm)\n"); + printf(" c compila IR->.c (plugin .wasm)\n"); + printf(" wasm compila IR->.wasm(plugin .wasm)\n"); + printf(" blocks lista os blocos .wasm\n"); + return 0; + } + fprintf(stderr, "comando desconhecido: %s\n", c); + return 2; +} diff --git a/tests/blocks_test.c b/tests/blocks_test.c new file mode 100644 index 0000000..7edbbd6 --- /dev/null +++ b/tests/blocks_test.c @@ -0,0 +1,35 @@ +/* prova: blocos .wasm carregam e assinam BlockLike/Renderable. */ +#include "catblocks/plugin.h" +#include +#include + +int main(void) { + const char *blocks[] = { + "add","subtract","multiply","divide","and","or","not", + "if","else","while","for","when_start" + }; + int n = sizeof(blocks)/sizeof(blocks[0]), fail = 0; + printf("%-12s %-8s %-8s %-9s %-5s %s\n", "bloco","BlockLike","Render","cor","cat","nome"); + for (int i = 0; i < n; i++) { + char path[128]; snprintf(path, sizeof path, "build/plugins/blocks/%s.wasm", blocks[i]); + char err[256]; + cb_plugin *p = cb_plugin_load_file(path, err, sizeof err); + if (!p) { printf("FAIL %s: %s\n", blocks[i], err); fail = 1; continue; } + int bl = cb_plugin_has_blocklike(p); + int rd = cb_plugin_has_renderable(p); + int col = cb_plugin_export_i32(p, "block_color", 0); + int cat = cb_plugin_export_i32(p, "block_cat", 0); + int nl = cb_plugin_export_i32(p, "block_name", 0); + char name[64] = "?"; + if (nl > 0 && nl < 63) { + int oa = 0; uint32_t msz = 0; + char *m = cb_plugin_outbuf(p, &oa, &msz); + if (m && oa >= 0 && oa + nl <= (int)msz) { memcpy(name, m + oa, nl); name[nl] = 0; } + } + printf("%-12s %-8d %-8d 0x%06X %-5d %s\n", blocks[i], bl, rd, col, cat, name); + if (!bl) { printf(" AVISO: %s sem BlockLike\n", blocks[i]); fail = 1; } + cb_plugin_free(p); + } + printf(fail ? "BLOCKS: FALHOU\n" : "BLOCKS: OK\n"); + return fail; +} diff --git a/tests/ir_test.c b/tests/ir_test.c new file mode 100644 index 0000000..3349227 --- /dev/null +++ b/tests/ir_test.c @@ -0,0 +1,32 @@ +/* prova ponta-a-ponta: interpreta o IR, gera .wat e .c, compila o .c com gcc. */ +#include "catblocks/ir.h" +#include "catblocks/programs.h" +#include +#include +#include + +char *cb_interp_run(cb_node *root, int nvars, char **out, size_t *outlen); + +int main(void) { + cb_node *root = cb_program_sum(); + + /* 1) interpretar */ + char *out = NULL; size_t olen = 0; + cb_interp_run(root, 4, &out, &olen); + printf("== interpretado ==\n%s", out ? out : "(vazio)"); + int interp_ok = out && strstr(out, "5050") != NULL; + + /* 2) gerar .wat e .c */ + cb_str wat, c; + cb_str_init(&wat); cb_emit_wat(root, &wat); + cb_str_init(&c); cb_emit_c(root, &c); + FILE *f = fopen("build/test_out.wat", "w"); fputs(wat.buf, f); fclose(f); + f = fopen("build/test_out.c", "w"); fputs(c.buf, f); fclose(f); + printf("== wat (%zu bytes) e c (%zu bytes) escritos ==\n", wat.len, c.len); + + cb_str_free(&wat); cb_str_free(&c); + free(out); + cb_node_free_all(NULL); + printf(interp_ok ? "IR: OK\n" : "IR: FALHOU\n"); + return interp_ok ? 0 : 1; +} diff --git a/tests/plugins_test.c b/tests/plugins_test.c new file mode 100644 index 0000000..69c34ec --- /dev/null +++ b/tests/plugins_test.c @@ -0,0 +1,64 @@ +/* prova: plugins .wasm compiladores produzem wat/c/wasm a partir do IR serializado. */ +#include "catblocks/plugin.h" +#include "catblocks/ir.h" +#include "catblocks/programs.h" +#include +#include +#include + +char *cb_interp_run(cb_node *root, int nvars, char **out, size_t *outlen); + +/* acumula a saida do "print" do wasm gerado */ +static char g_print[4096]; static size_t g_plen; +static int host_print(wasm_inst *in, const wval *args, wval *ret, void *ud) { + (void)in; (void)ret; (void)ud; + char b[32]; int n = snprintf(b, sizeof b, "%d\n", (int)(int32_t)args[0]); + if (g_plen + n < sizeof g_print) { memcpy(g_print+g_plen, b, n); g_plen += n; g_print[g_plen]=0; } + return 0; +} + +int main(void) { + cb_node *root = cb_program_sum(); + cb_str ir; cb_str_init(&ir); cb_ir_serialize(root, &ir); + printf("== IR serializado (%zu bytes) ==\n%s", ir.len, ir.buf); + + char err[256]; + /* 1) plugin wat */ + cb_plugin *pw = cb_plugin_load_file("build/plugins/compiler_wat.wasm", err, sizeof err); + if (!pw) { fprintf(stderr, "wat: %s\n", err); return 1; } + size_t n; char *wat = cb_plugin_run(pw, ir.buf, ir.len, &n); + printf("== WAT (%zu bytes) ==\n%s", n, wat ? wat : "(erro)"); + FILE *f = fopen("build/plugin_out.wat","w"); fputs(wat,f); fclose(f); + free(wat); cb_plugin_free(pw); + + /* 2) plugin c */ + cb_plugin *pc = cb_plugin_load_file("build/plugins/compiler_c.wasm", err, sizeof err); + if (!pc) { fprintf(stderr, "c: %s\n", err); return 1; } + char *c = cb_plugin_run(pc, ir.buf, ir.len, &n); + printf("== C (%zu bytes) ==\n%s", n, c ? c : "(erro)"); + f = fopen("build/plugin_out.c","w"); fputs(c,f); fclose(f); + free(c); cb_plugin_free(pc); + + /* 3) plugin wasm -> binario; corre-o no interpretador com o print do host */ + cb_plugin *pwm = cb_plugin_load_file("build/plugins/compiler_wasm.wasm", err, sizeof err); + if (!pwm) { fprintf(stderr, "wasm: %s\n", err); return 1; } + char *wasmb = cb_plugin_run(pwm, ir.buf, ir.len, &n); + printf("== WASM gerado: %zu bytes ==\n", n); + f = fopen("build/plugin_out.wasm","wb"); fwrite(wasmb,1,n,f); fclose(f); + + char e2[256]; + wasm_module *m = wasm_load((uint8_t*)wasmb, n, e2, sizeof e2); + if (!m) { fprintf(stderr, "load gerado: %s\n", e2); return 1; } + wasm_import_def imp[1] = { {"catblocks","print",host_print,NULL} }; + wasm_inst *in = wasm_instantiate(m, imp, 1, 4, e2, sizeof e2); + if (!in) { fprintf(stderr, "inst gerado: %s\n", e2); return 1; } + wval r = 0; + if (wasm_call(in, "main", NULL, 0, &r)) { fprintf(stderr, "run gerado: %s\n", wasm_error(in)); return 1; } + printf("== saida do wasm gerado ==\n%s", g_print); + int ok = strstr(g_print, "5050") != NULL; + free(wasmb); cb_plugin_free(pwm); + wasm_free(in); wasm_module_free(m); + cb_str_free(&ir); cb_node_free_all(NULL); + printf(ok ? "PLUGINS: OK\n" : "PLUGINS: FALHOU\n"); + return ok ? 0 : 1; +} diff --git a/tests/run.sh b/tests/run.sh new file mode 100755 index 0000000..253617f --- /dev/null +++ b/tests/run.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# catblocks - prova ponta-a-ponta: interpretar + gerar .wat + gerar .c + +# compilar o .c com gcc e correr + gerar .wasm e correr no interpretador. +set -e +cd "$(dirname "$0")/.." +BIN=build/linux/x86_64/bin/catblocks +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +echo "== 1) interpretador WASM (smoke) ==" +NDK=${NDK:-/home/ovelha/android-sdk/ndk/android-ndk-r26d} +export PATH=/home/ovelha/wasmbin:$PATH +"$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/clang" --target=wasm32 -nostdlib -O2 \ + -Wl,--no-entry -Wl,--export-all -o "$TMP/demo.wasm" tests/wasm_demo.c +gcc -std=c11 -O2 -Iinclude src/catblocks/wasm.c tests/wasm_smoke.c -o "$TMP/wasm_smoke" +"$TMP/wasm_smoke" "$TMP/demo.wasm" + +echo "== 2) interpretador de IR + emissores internos ==" +gcc -std=c11 -O2 -Iinclude src/catblocks/ir.c src/catblocks/interp.c src/catblocks/programs.c \ + tests/ir_test.c -o "$TMP/ir_test" +"$TMP/ir_test" + +echo "== 3) plugins .wasm (IR->wat/c/wasm) ==" +gcc -std=c11 -O2 -Iinclude src/catblocks/ir.c src/catblocks/wasm.c src/catblocks/plugin.c \ + src/catblocks/programs.c tests/plugins_test.c -o "$TMP/plugins_test" +"$TMP/plugins_test" + +echo "== 4) blocos .wasm (BlockLike/Renderable) ==" +gcc -std=c11 -O2 -Iinclude src/catblocks/wasm.c src/catblocks/plugin.c tests/blocks_test.c \ + -o "$TMP/blocks_test" +"$TMP/blocks_test" + +echo "== 5) CLI: run / ir / wat / c / wasm / blocks ==" +"$BIN" run +"$BIN" wat +"$BIN" c +"$BIN" wasm +"$BIN" blocks + +echo "== 6) compilar o .c gerado com gcc e correr ==" +gcc build/catblocks_out.c -o "$TMP/gen_c" +OUT=$("$TMP/gen_c") +echo "saida C gerada: $OUT" +[ "$OUT" = "5050" ] || { echo "FALHOU: esperado 5050"; exit 1; } + +echo "== TUDO OK ==" diff --git a/tests/wasm_demo.c b/tests/wasm_demo.c new file mode 100644 index 0000000..d1835d7 --- /dev/null +++ b/tests/wasm_demo.c @@ -0,0 +1,13 @@ +/* modulo de exemplo compilado para wasm32 (sem libc) */ +__attribute__((visibility("default"))) int add(int a, int b) { return a + b; } +__attribute__((visibility("default"))) int sum_to(int n) { + int s = 0; + for (int i = 1; i <= n; i++) s += i; + return s; +} +__attribute__((visibility("default"))) int fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); } +__attribute__((visibility("default"))) int fib(int n) { + int a = 0, b = 1; + for (int i = 0; i < n; i++) { int t = a + b; a = b; b = t; } + return a; +} diff --git a/tests/wasm_smoke.c b/tests/wasm_smoke.c new file mode 100644 index 0000000..eed8859 --- /dev/null +++ b/tests/wasm_smoke.c @@ -0,0 +1,44 @@ +/* prova que o interpretador carrega e chama exports de um .wasm real */ +#include "catblocks/wasm.h" +#include +#include +#include + +static int chk(wasm_inst *in, const char *name, int nargs, int a0, int a1, int want) { + wval args[2], r = 0; + args[0] = wv_i32(a0); args[1] = wv_i32(a1); + if (wasm_call(in, name, args, nargs, &r)) { + printf("FAIL %s: %s\n", name, wasm_error(in)); return 1; + } + int got = (int)(int32_t)r; + printf("%-8s(%-4d%s) = %-6d esperado %-6d %s\n", name, a0, + nargs==2 ? ",2" : "", got, want, got==want ? "OK" : "FAIL"); + return got != want; +} + +int main(int argc, char **argv) { + if (argc < 2) { fprintf(stderr, "uso: %s arquivo.wasm\n", argv[0]); return 2; } + FILE *f = fopen(argv[1], "rb"); + if (!f) { perror("fopen"); return 1; } + fseek(f, 0, SEEK_END); long n = ftell(f); fseek(f, 0, SEEK_SET); + uint8_t *buf = malloc(n); + if (fread(buf, 1, n, f) != (size_t)n) { fprintf(stderr, "read falhou\n"); return 1; } + fclose(f); + char err[256]; + wasm_module *m = wasm_load(buf, n, err, sizeof(err)); + if (!m) { fprintf(stderr, "load: %s\n", err); return 1; } + printf("imports=%d\n", wasm_import_count(m)); + wasm_inst *in = wasm_instantiate(m, NULL, 0, 16, err, sizeof(err)); + if (!in) { fprintf(stderr, "instantiate: %s\n", err); return 1; } + int fail = 0; + fail |= chk(in, "add", 2, 40, 2, 42); + fail |= chk(in, "sum_to", 1, 10, 0, 55); + fail |= chk(in, "sum_to", 1, 100, 0, 5050); + fail |= chk(in, "fact", 1, 5, 0, 120); + fail |= chk(in, "fact", 1, 7, 0, 5040); + fail |= chk(in, "fib", 1, 10, 0, 55); + fail |= chk(in, "fib", 1, 12, 0, 144); + wasm_free(in); wasm_module_free(m); free(buf); + printf(fail ? "SMOKE: FALHOU\n" : "SMOKE: OK\n"); + return fail; +}