From 630a1686e50a6e5fd4831ac184dd0caac32d0060 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Fri, 23 Oct 2026 17:08:13 -0300 Subject: [PATCH] =?UTF-8?q?Executor=20compila=20express=C3=B5es=20puras;?= =?UTF-8?q?=20texto=20=3D=20TEXTO=20n=C3=A3o=20lia=20al=C3=A9m=20do=20fim?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Traço novo no core: tb_type_block_set_pure (TB_PURE_NUM/LT/EQ/GT/AND/ OR/NOT/VAR). A library declara que o bloco é puro e qual a semântica; number e operators definem cada conta como uma função de doubles, que é ao mesmo tempo o eval do bloco e o que um executor compila. tb_editor_jit.c: ao montar a árvore do runtime, uma expressão de blocos puros vira um bloco só (Editor.Compiled), com nós nativos (double, variável resolvida para o slot), sem marcar/avaliar/copiar valor em cada nó. O que não é puro (item de lista, Meus Blocos...) entra como nó que avalia a árvore normal. TINYBLOCKS_NO_JIT=1 desliga. Render do Minecraft: 18 ms -> 12 ms, com a mesma imagem (checksum). O "=" e o "<" entre textos passavam do fim da string: o | 32 vinha antes do teste do fim, e "abc" = "ABC" dava falso. tests/vm_bench.c (make bench-vm BENCH=projeto.json) mede a VM sem janela; TINYBLOCKS_VM_MS troca a fatia de tempo da VM por quadro. Co-Authored-By: Claude Opus 5.5 --- Makefile | 31 +- include/tinyblocks/tb_type_block.h | 25 ++ libraries/tinyblocks-editor/Makefile | 8 +- .../include/tb_editor_internal.h | 9 + libraries/tinyblocks-editor/src/tb_editor.c | 25 +- .../tinyblocks-editor/src/tb_editor_jit.c | 285 ++++++++++++++++++ libraries/tinyblocks-number/src/tb_number.c | 141 +++++---- .../tinyblocks-operators/src/tb_operators.c | 144 ++++----- src/tb_type_block.c | 8 + tests/editor_harness.c | 35 +++ tests/meta_test.c | 6 +- tests/stdlib_test.c | 2 + tests/vm_bench.c | 127 ++++++++ 13 files changed, 694 insertions(+), 152 deletions(-) create mode 100644 libraries/tinyblocks-editor/src/tb_editor_jit.c create mode 100644 tests/vm_bench.c diff --git a/Makefile b/Makefile index 152a69b..6df4caf 100644 --- a/Makefile +++ b/Makefile @@ -450,7 +450,7 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(EIMG_DIR)/include/tb_editor_image.h \ $(EFILES_DIR)/include/tb_editor_files.h \ $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h \ - $(EDITOR_SRC)/tb_editor_mcp.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ + $(EDITOR_SRC)/tb_editor_mcp.c $(EDITOR_SRC)/tb_editor_jit.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ lib-blueprint ed-modules @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) \ @@ -460,13 +460,40 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ $(EDITOR_SRC)/tb_editor_modules.c \ $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c \ - $(EDITOR_SRC)/tb_editor_mcp.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ + $(EDITOR_SRC)/tb_editor_mcp.c $(EDITOR_SRC)/tb_editor_jit.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ $(BP_DIR)/src/blueprint.c $(BP_DIR)/src/serialize.c \ $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic +$(BUILD)/vm_bench: tests/vm_bench.c $(IMG_DIR)/src/tb_imglib.c $(SRCS) \ + $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ + $(EDITOR_SRC)/tb_editor_modules.c \ + $(EW_DIR)/include/tb_editor_widgets.h \ + $(EIMG_DIR)/include/tb_editor_image.h \ + $(EFILES_DIR)/include/tb_editor_files.h \ + $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c $(A11Y_DIR)/include/tb_a11y.h \ + $(EDITOR_SRC)/tb_editor_mcp.c $(EDITOR_SRC)/tb_editor_jit.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ + lib-blueprint ed-modules + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_REL) -g -I$(IMG_DIR)/include \ + -I$(ED_DIR)/include -I$(A11Y_DIR)/include -I$(MCPS_DIR)/include -DTB_EDITOR_PRIVATE_API -DTB_MCP_SERVER_PRIVATE_API -I$(EW_DIR)/include -I$(EIMG_DIR)/include -I$(EFILES_DIR)/include -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include -I$(SYN_DIR)/include -I$(SB_DIR)/include \ + $(SRCS) \ + $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ + $(EDITOR_SRC)/tb_editor_modules.c \ + $(GX_DIR)/src/tb_graphics.c $(A11Y_DIR)/src/tb_a11y.c \ + $(EDITOR_SRC)/tb_editor_mcp.c $(EDITOR_SRC)/tb_editor_jit.c $(MCPS_DIR)/src/tb_mcp_server.c $(MCPS_DIR)/src/tb_mcp_http.c \ + $(BP_DIR)/src/blueprint.c $(BP_DIR)/src/serialize.c \ + $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ + $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ + $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ + $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c $(SYN_DIR)/src/tb_syntax.c $(SB_DIR)/src/tb_scratchblocks.c $(IMG_DIR)/src/tb_imglib.c tests/vm_bench.c -o $@ -ldl -lm -rdynamic + +bench-vm: $(BUILD)/vm_bench ## Mede a VM do editor num projeto (BENCH=projeto.json) + ./$(BUILD)/vm_bench $(BENCH) 10 + test-editor: $(BUILD)/editor_harness ## Roda o harness headless do editor (ASan/UBSan) ./$(BUILD)/editor_harness diff --git a/include/tinyblocks/tb_type_block.h b/include/tinyblocks/tb_type_block.h index 51c9046..bd8ef6e 100644 --- a/include/tinyblocks/tb_type_block.h +++ b/include/tinyblocks/tb_type_block.h @@ -84,6 +84,29 @@ struct TinyBlocks_TypeBlock { campos separados por '|'. Ex.: "liste as ferramentas de %1". */ const char* label; const char* label_defaults; + + /* Semantica pura (opcional, TB_PURE_*): o executor pode compilar o bloco + numa expressao nativa em vez de avaliar no por no. Ver + tb_type_block_set_pure. */ + int pure; + double (*pure_num)(const double* x); + uint32_t pure_arity; +}; + +/* Semanticas puras que um executor sabe compilar. Quem declara garante que o + * bloco nao tem efeito colateral e que a saida e exatamente: + * NUM: o numero pure_num(x), com x[i] = entrada i como numero (sem numero + * = 0); inteiro se der exato, senao real. + * LT/EQ/GT: 1/0; numeros se as duas entradas forem numeros, senao o texto + * sem diferenciar maiusculas (como o "<" do Scratch). + * AND/OR/NOT: 1/0 pela verdade (tb_value_truthy) das entradas. + * VAR: o valor da variavel com o nome da entrada 0 (sem variavel = 0). */ +enum { + TB_PURE_NONE = 0, + TB_PURE_NUM, + TB_PURE_LT, TB_PURE_EQ, TB_PURE_GT, + TB_PURE_AND, TB_PURE_OR, TB_PURE_NOT, + TB_PURE_VAR, }; /* -- Forma e tracos --- */ @@ -94,6 +117,8 @@ TB_API void tb_type_block_set_flags(TinyBlocks_TypeBlock* tb, uint32_t flags); TB_API void tb_type_block_set_event(TinyBlocks_TypeBlock* tb, const char* event); /* Rotulo do bloco no editor (%N = entrada N) e valores iniciais "a|b|c" */ TB_API void tb_type_block_set_label(TinyBlocks_TypeBlock* tb, const char* label, const char* defaults); +/* Declara a semantica pura do bloco (TB_PURE_*); num/arity so para NUM */ +TB_API void tb_type_block_set_pure(TinyBlocks_TypeBlock* tb, int pure, double (*num)(const double* x), uint32_t arity); TB_API void tb_type_block_set_input_flags (TinyBlocks_TypeBlock* tb, uint32_t i, uint32_t flags); TB_API void tb_type_block_set_output_flags(TinyBlocks_TypeBlock* tb, uint32_t i, uint32_t flags); TB_API uint32_t tb_type_block_input_flags (const TinyBlocks_TypeBlock* tb, uint32_t i); diff --git a/libraries/tinyblocks-editor/Makefile b/libraries/tinyblocks-editor/Makefile index 65806cd..e5779ca 100644 --- a/libraries/tinyblocks-editor/Makefile +++ b/libraries/tinyblocks-editor/Makefile @@ -5,7 +5,7 @@ CC := gcc BUILD := build CORE := ../../build -CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ +CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \ -D_POSIX_C_SOURCE=200809L -DTB_EDITOR_PRIVATE_API \ -I../../include -Iinclude \ -I../tinyblocks-graphics/include \ @@ -29,7 +29,7 @@ IMG_A := $(IMG_DIR)/build/libtinyblocks-editor-image.a FILES_DIR := libraries/tinyblocks-editor-files FILES_A := $(FILES_DIR)/build/libtinyblocks-editor-files.a -OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o $(BUILD)/tb_editor_modules.o $(BUILD)/tb_editor_mcp.o +OBJ := $(BUILD)/tb_editor.o $(BUILD)/tb_stage_widget.o $(BUILD)/tb_editor_modules.o $(BUILD)/tb_editor_mcp.o $(BUILD)/tb_editor_jit.o LIB_A := $(BUILD)/libtinyblocks-editor.a LIB_SO := $(BUILD)/libtinyblocks-editor.so @@ -60,6 +60,10 @@ $(BUILD)/tb_editor_mcp.o: src/tb_editor_mcp.c include/tb_editor_internal.h \ @mkdir -p $(BUILD) $(CC) $(CFLAGS) -fPIC -c $< -o $@ +$(BUILD)/tb_editor_jit.o: src/tb_editor_jit.c include/tb_editor_internal.h ../../include/tinyblocks/tb_type_block.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + $(BUILD)/tb_stage_widget.o: src/tb_stage_widget.c include/tb_stage_widget.h \ ../tinyblocks-graphics/include/tb_graphics.h @mkdir -p $(BUILD) diff --git a/libraries/tinyblocks-editor/include/tb_editor_internal.h b/libraries/tinyblocks-editor/include/tb_editor_internal.h index 59381c0..9346a18 100644 --- a/libraries/tinyblocks-editor/include/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/include/tb_editor_internal.h @@ -1072,6 +1072,15 @@ const char* mouth_label(const TinyBlocks_TypeBlock* t, int k); int input_count(const TinyBlocks_TypeBlock* t); bool slot_is_bool(const TinyBlocks_TypeBlock* t, int i); const char* slot_src(const EdBlock* b, int s); + +/* -- Executor: arvore do runtime e compilador de expressoes (tb_editor_jit.c) -- */ +TinyBlocks_Value value_from_text(const char* raw, TinyBlocks_ValueKind k); +void run_track(Ed* ed, TinyBlocks_Block* b); +TinyBlocks_TypeBlock* blk_type(Ed* ed, EdBlock* b); +TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi); +void rt_mark_dirty(TinyBlocks_Block* r, int depth); +/* Compila a expressao pura que comeca em bi num bloco so (NULL = nao deu) */ +TinyBlocks_Block* jit_build(Ed* ed, Tab* T, int bi); int cat_of(Ed* ed, const char* type_name); const BlockSpec* spec_of_type(const TinyBlocks_TypeBlock* t); void ax_block_label(Tab* T, int bi, char* out, size_t cap, int depth); /* "repita (10) vezes" */ diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index 9878744..6cf5f5c 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -126,7 +126,7 @@ static void draw_bump(TinyBlocks_RenderableBlock* rb, float x, float y, Col c, C /* Converte o texto de um campo no valor esperado pelo slot. * Slots sem tipo (NONE) adivinham: inteiro, real ou texto. */ -static TinyBlocks_Value value_from_text(const char* raw, TinyBlocks_ValueKind k) { +TinyBlocks_Value value_from_text(const char* raw, TinyBlocks_ValueKind k) { char* e; switch (k) { case TB_VALUE_INTEGER: { @@ -1262,7 +1262,7 @@ static void run_reset(Ed* ed) { tb_variables_reset_blocks(); } -static void run_track(Ed* ed, TinyBlocks_Block* b) { +void run_track(Ed* ed, TinyBlocks_Block* b) { if (ed->run_n >= ed->run_cap) { int nc = ed->run_cap ? ed->run_cap*2 : 256; TinyBlocks_Block** p = realloc(ed->run_blocks, (size_t)nc * sizeof(*p)); @@ -1272,16 +1272,20 @@ static void run_track(Ed* ed, TinyBlocks_Block* b) { ed->run_blocks[ed->run_n++] = b; } -static TinyBlocks_TypeBlock* blk_type(Ed* ed, EdBlock* b) { +TinyBlocks_TypeBlock* blk_type(Ed* ed, EdBlock* b) { if (!b->type && b->type_name[0]) b->type = tb_type_block_find(ed->rt, b->type_name); return b->type; } /* Converte o bloco bi (e seus repórteres) em uma árvore de blocos do runtime */ -static TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) { +TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) { EdBlock* b = &T->ws[bi]; TinyBlocks_TypeBlock* t = blk_type(ed, b); if (!t) return NULL; + if (t->pure && t->pure != TB_PURE_VAR) { /* expressao pura: compila */ + TinyBlocks_Block* c = jit_build(ed, T, bi); + if (c) return c; + } if (ed->run_n >= MAX_RUN_BLOCKS) { run_abort(ed, "limite de blocos em execução atingido"); return NULL; } TinyBlocks_Block* r = tb_block_create(ed->rt, t); if (!r) return NULL; @@ -1315,7 +1319,7 @@ static void rt_cache_clear(Ed* ed) { } /* Marca a arvore inteira como "suja" para ser reavaliada */ -static void rt_mark_dirty(TinyBlocks_Block* r, int depth) { +void rt_mark_dirty(TinyBlocks_Block* r, int depth) { if (!r || depth > 64) return; r->dirty = true; for (uint32_t i = 0; i < r->input_count; i++) @@ -1393,6 +1397,15 @@ static bool step(Ed* ed) { * avanca as threads varias vezes no mesmo quadro ate todas pausarem ou * terminarem. O corpo de Meus Blocos roda no mesmo executor, sem pausas. */ #define VM_FRAME_MS 12u +/* TINYBLOCKS_VM_MS troca a fatia (profiling: uma fatia grande roda tudo num quadro) */ +static unsigned vm_frame_ms(void) { + static unsigned ms = 0; + if (!ms) { + const char* e = getenv("TINYBLOCKS_VM_MS"); + ms = e && atoi(e) > 0 ? (unsigned)atoi(e) : VM_FRAME_MS; + } + return ms; +} static unsigned now_ms(void); static const TinyBlocks_FlowClass* frame_flow(Ed* ed, VmFrame* f) { @@ -1577,7 +1590,7 @@ static void vm_frame(Ed* ed) { else { tb_vars_scope_set(NULL); tb_vars_scope_free(th->scope); th->scope = NULL; } tb_vars_scope_set(NULL); } - } while (alive && !ed->abort && !ed->redraw_req && now_ms() - t0 < VM_FRAME_MS); + } while (alive && !ed->abort && !ed->redraw_req && now_ms() - t0 < vm_frame_ms()); cap_end(ed); if (!alive || ed->abort) { run_end(ed); diff --git a/libraries/tinyblocks-editor/src/tb_editor_jit.c b/libraries/tinyblocks-editor/src/tb_editor_jit.c new file mode 100644 index 0000000..d6d1165 --- /dev/null +++ b/libraries/tinyblocks-editor/src/tb_editor_jit.c @@ -0,0 +1,285 @@ +/* + * tb_editor_jit.c - compilador de expressoes do executor do editor. + * + * Uma expressao feita de blocos puros (os que a library declara com + * tb_type_block_set_pure: contas, comparacoes, logica, "valor de variavel") + * vira um bloco so, "Editor.Compiled", com a expressao numa arvore compacta + * de nos nativos: numeros em double, variaveis resolvidas uma vez para o + * slot (TbVarRef), sem marcar/avaliar/copiar valor em cada no. + * + * O que nao e puro (item de lista, pergunta, "Meus Blocos"...) entra como no + * GEN: a arvore normal do runtime daquele bloco, avaliada como antes. A + * semantica de cada no e a declarada pelo traco TB_PURE_* (tb_type_block.h). + */ +#include +#include +#include +#include +#include +#include +#include +#include "tb_editor_internal.h" + +enum { J_CONST, J_VAR, J_GEN, J_NUM, J_CMP, J_AND, J_OR, J_NOT }; + +#define JIT_MAX_NODES 256 +#define JIT_MAX_ARGS 4 + +typedef struct { + int op; + int pure; /* J_CMP: TB_PURE_LT/EQ/GT */ + int arg[JIT_MAX_ARGS]; + int argc; + double (*fn)(const double* x); /* J_NUM */ + double k; /* J_CONST: como numero */ + bool k_num; /* J_CONST: o valor e numero? */ + TinyBlocks_Value cval; /* J_CONST: valor original (owned) */ + TinyBlocks_Block* gen; /* J_GEN (dono: run_blocks do editor) */ + TbVarRef ref; /* J_VAR */ + char name[64]; /* J_VAR */ +} JNode; + +typedef struct { + TinyBlocks* rt; + int n, root; + JNode node[]; +} JProg; + +typedef struct { /* compilacao em andamento */ + Ed* ed; + Tab* T; + JNode node[JIT_MAX_NODES]; + int n; + bool fail; +} JCtx; + +/* -- Compilacao --- */ + +static int add_node(JCtx* c) { + if (c->n >= JIT_MAX_NODES) { c->fail = true; return -1; } + JNode* x = &c->node[c->n]; + memset(x, 0, sizeof(*x)); + return c->n++; +} + +static int compile_block(JCtx* c, int bi); + +/* Entrada s do bloco bi: o bloco encaixado ou a constante do campo */ +static int compile_slot(JCtx* c, int bi, int s) { + EdBlock* b = &c->T->ws[bi]; + if (b->args[s] >= 0) return compile_block(c, b->args[s]); + int i = add_node(c); + if (i < 0) return -1; + JNode* x = &c->node[i]; + x->op = J_CONST; + const char* raw = slot_src(b, s); + x->cval = raw[0] ? value_from_text(raw, b->type->input_descs[s].expected_kind) : tb_value_none(); + double d; + x->k_num = tb_value_to_number(x->cval, &d); + x->k = x->k_num ? d : 0.0; + return i; +} + +static int compile_gen(JCtx* c, int bi) { + TinyBlocks_Block* r = build_rt(c->ed, c->T, bi); + if (!r || r->output_count == 0) { c->fail = true; return -1; } + int i = add_node(c); + if (i < 0) return -1; + c->node[i].op = J_GEN; + c->node[i].gen = r; + return i; +} + +static int compile_block(JCtx* c, int bi) { + if (c->fail) return -1; + EdBlock* b = &c->T->ws[bi]; + TinyBlocks_TypeBlock* t = blk_type(c->ed, b); + if (!t) { c->fail = true; return -1; } + int nin = (int)t->input_desc_count; + switch (t->pure) { + case TB_PURE_VAR: { + if (nin < 1 || b->args[0] >= 0) return compile_gen(c, bi); /* nome calculado */ + const char* nm = slot_src(b, 0); + if (!nm[0] || strlen(nm) >= sizeof(c->node[0].name)) return compile_gen(c, bi); + int i = add_node(c); + if (i < 0) return -1; + c->node[i].op = J_VAR; + strcpy(c->node[i].name, nm); + c->node[i].ref.fixed = true; /* o nome fica no no: nunca muda */ + return i; + } + case TB_PURE_NUM: + case TB_PURE_LT: case TB_PURE_EQ: case TB_PURE_GT: + case TB_PURE_AND: case TB_PURE_OR: case TB_PURE_NOT: { + int argc = t->pure == TB_PURE_NUM ? (int)t->pure_arity : t->pure == TB_PURE_NOT ? 1 : 2; + if (argc > JIT_MAX_ARGS || argc > nin || (t->pure == TB_PURE_NUM && !t->pure_num)) + return compile_gen(c, bi); + int i = add_node(c); + if (i < 0) return -1; + int a[JIT_MAX_ARGS]; + for (int k = 0; k < argc; k++) a[k] = compile_slot(c, bi, k); + if (c->fail) return -1; + JNode* x = &c->node[i]; + x->argc = argc; + for (int k = 0; k < argc; k++) x->arg[k] = a[k]; + x->pure = t->pure; + x->fn = t->pure_num; + x->op = t->pure == TB_PURE_NUM ? J_NUM : t->pure == TB_PURE_AND ? J_AND + : t->pure == TB_PURE_OR ? J_OR : t->pure == TB_PURE_NOT ? J_NOT : J_CMP; + return i; + } + default: + return compile_gen(c, bi); + } +} + +/* -- Execucao --- */ + +static double jnum(JProg* P, int i); + +/* Bloco nao compilado: reavalia a arvore dele (como o executor faria) */ +static TinyBlocks_Value gen_eval(JProg* P, JNode* x) { + rt_mark_dirty(x->gen, 0); + tb_block_eval(x->gen, P->rt); + return x->gen->outputs[0]; +} + +/* Valor (emprestado) de um no; contas viram numero em *tmp */ +static TinyBlocks_Value jval(JProg* P, int i, TinyBlocks_Value* tmp) { + JNode* x = &P->node[i]; + switch (x->op) { + case J_CONST: return x->cval; + case J_VAR: { + const TinyBlocks_Value* v = tb_vars_get_ref(x->name, &x->ref); + return v ? *v : tb_value_integer(0); + } + case J_GEN: return gen_eval(P, x); + default: { + double d = jnum(P, i); + *tmp = (d == floor(d) && fabs(d) < 9e15) ? tb_value_integer((int64_t)d) : tb_value_real(d); + return *tmp; + } + } +} + +/* Texto sem diferenciar maiusculas (ASCII), como o "=" do Scratch */ +static int icmp(const char* a, const char* b) { + for (;; a++, b++) { + int ca = tolower((unsigned char)*a), cb = tolower((unsigned char)*b); + if (ca != cb || !ca) return (ca > cb) - (ca < cb); + } +} + +static int jcmp(JProg* P, JNode* x) { + TinyBlocks_Value ta, tb2; + TinyBlocks_Value a = jval(P, x->arg[0], &ta); + double p, q; + bool an = tb_value_to_number(a, &p); + char sa[256] = ""; + if (!an) tb_value_to_text(a, sa, sizeof(sa)); /* antes de avaliar b (pode reusar a saida) */ + TinyBlocks_Value b = jval(P, x->arg[1], &tb2); + bool bn = tb_value_to_number(b, &q); + if (an && bn) return (p > q) - (p < q); + char sb[256]; + if (an) tb_value_to_text(a, sa, sizeof(sa)); + tb_value_to_text(b, sb, sizeof(sb)); + return icmp(sa, sb); +} + +static bool jtruth(JProg* P, int i) { + JNode* x = &P->node[i]; + if (x->op == J_CONST || x->op == J_VAR || x->op == J_GEN) { + TinyBlocks_Value t; + return tb_value_truthy(jval(P, i, &t)); + } + return jnum(P, i) != 0.0; +} + +static double jnum(JProg* P, int i) { + JNode* x = &P->node[i]; + switch (x->op) { + case J_CONST: return x->k; + case J_VAR: { + const TinyBlocks_Value* v = tb_vars_get_ref(x->name, &x->ref); + if (!v) return 0.0; + if (v->kind == TB_VALUE_INTEGER) return (double)v->as.integer; + if (v->kind == TB_VALUE_REAL) return v->as.real; + return tb_value_as_number(*v, 0); + } + case J_GEN: return tb_value_as_number(gen_eval(P, x), 0); + case J_NUM: { + double a[JIT_MAX_ARGS]; + for (int k = 0; k < x->argc; k++) a[k] = jnum(P, x->arg[k]); + return x->fn(a); + } + case J_CMP: { + int r = jcmp(P, x); + return (x->pure == TB_PURE_LT ? r < 0 : x->pure == TB_PURE_EQ ? r == 0 : r > 0) ? 1.0 : 0.0; + } + case J_AND: { bool a = jtruth(P, x->arg[0]), b = jtruth(P, x->arg[1]); return a && b; } + case J_OR: { bool a = jtruth(P, x->arg[0]), b = jtruth(P, x->arg[1]); return a || b; } + case J_NOT: return !jtruth(P, x->arg[0]); + } + return 0.0; +} + +/* -- Bloco "Editor.Compiled" --- */ + +static void eval_compiled(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + JProg* P = self->userdata; + double d = P ? jnum(P, P->root) : 0.0; + if (isfinite(d) && d == floor(d) && fabs(d) < 9e15) tb_block_set_output(self, 0, tb_value_integer((int64_t)d)); + else tb_block_set_output(self, 0, tb_value_real(isfinite(d) ? d : 0.0)); + self->dirty = false; +} + +static void deinit_compiled(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + JProg* P = self->userdata; + if (!P) return; + for (int i = 0; i < P->n; i++) + if (P->node[i].op == J_CONST) tb_value_free(&P->node[i].cval); +} + +static TinyBlocks_TypeBlock* compiled_type(TinyBlocks* rt) { + TinyBlocks_TypeBlock* t = tb_type_block_find(rt, "Editor.Compiled"); + if (t) return t; + static const TinyBlocks_SlotDesc out[] = {{"valor", TB_VALUE_NONE}}; + t = tb_type_block_create(rt, "Editor.Compiled", NULL, 0, out, 1, eval_compiled); + if (!t) return NULL; + tb_type_block_set_flags(t, TB_TYPE_HIDDEN); + tb_type_block_set_instance_hooks(t, 0, NULL, deinit_compiled); + return t; +} + +TinyBlocks_Block* jit_build(Ed* ed, Tab* T, int bi) { + const char* off = getenv("TINYBLOCKS_NO_JIT"); + if (off && off[0] && off[0] != '0') return NULL; + TinyBlocks_TypeBlock* ct = compiled_type(ed->rt); + if (!ct) return NULL; + JCtx* c = calloc(1, sizeof(JCtx)); + if (!c) return NULL; + c->ed = ed; c->T = T; + int root = compile_block(c, bi); + TinyBlocks_Block* r = NULL; + if (!c->fail && root >= 0 && c->node[root].op != J_GEN && c->node[root].op != J_CONST) { + r = tb_block_create(ed->rt, ct); + JProg* P = r ? tb_alloc(ed->rt, sizeof(JProg) + (size_t)c->n * sizeof(JNode)) : NULL; + if (P) { + P->rt = ed->rt; + P->n = c->n; + P->root = root; + memcpy(P->node, c->node, (size_t)c->n * sizeof(JNode)); + r->userdata = P; + run_track(ed, r); + c->n = 0; /* os valores agora sao do P */ + } else if (r) { + tb_block_destroy(r, ed->rt); + r = NULL; + } + } + for (int i = 0; i < c->n; i++) if (c->node[i].op == J_CONST) tb_value_free(&c->node[i].cval); + free(c); + return r; +} diff --git a/libraries/tinyblocks-number/src/tb_number.c b/libraries/tinyblocks-number/src/tb_number.c index 65498ab..66c24f1 100644 --- a/libraries/tinyblocks-number/src/tb_number.c +++ b/libraries/tinyblocks-number/src/tb_number.c @@ -84,34 +84,37 @@ static double trig(double x) { return tb_number_round_to(x, 10); } #define N(i) tb_block_input_number(self, rt, (i), 0) -static void eval_div(TinyBlocks_Block* self, TinyBlocks* rt) { - double b = N(1); - out_num(self, b == 0.0 ? 0.0 : N(0) / b); +/* Blocos puros: a funcao de doubles e a definicao do bloco. O eval le as + * entradas e chama a mesma funcao que um executor compila (TB_PURE_NUM). */ +static double f_div(const double* x) { return x[1] == 0.0 ? 0.0 : x[0] / x[1]; } +static double f_pow(const double* x) { return pow(x[0], x[1]); } +static double f_sqrt(const double* x) { return x[0] < 0 ? 0.0 : sqrt(x[0]); } +static double f_round(const double* x) { return round(x[0]); } +static double f_floor(const double* x) { return floor(x[0]); } +static double f_ceil(const double* x) { return ceil(x[0]); } +static double f_round_to(const double* x) { return tb_number_round_to(x[0], (int)x[1]); } +static double f_sin(const double* x) { return trig(sin(x[0] * DEG)); } +static double f_cos(const double* x) { return trig(cos(x[0] * DEG)); } +static double f_tan(const double* x) { return trig(tan(x[0] * DEG)); } +static double f_asin(const double* x) { return (x[0] < -1 || x[0] > 1) ? 0.0 : trig(asin(x[0]) / DEG); } +static double f_acos(const double* x) { return (x[0] < -1 || x[0] > 1) ? 0.0 : trig(acos(x[0]) / DEG); } +static double f_atan(const double* x) { return trig(atan(x[0]) / DEG); } +static double f_log10(const double* x) { return x[0] > 0 ? log10(x[0]) : 0.0; } +static double f_ln(const double* x) { return x[0] > 0 ? log(x[0]) : 0.0; } +static double f_exp(const double* x) { return exp(x[0]); } +static double f_pi(const double* x) { (void)x; return M_PI; } +static double f_clamp(const double* x) { + double lo = x[1], hi = x[2]; + if (lo > hi) { double t = lo; lo = hi; hi = t; } + return x[0] < lo ? lo : x[0] > hi ? hi : x[0]; } -static void eval_pow(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, pow(N(0), N(1))); } -static void eval_sqrt(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x < 0 ? 0.0 : sqrt(x)); } -static void eval_round(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, round(N(0))); } -static void eval_floor(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, floor(N(0))); } -static void eval_ceil(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, ceil(N(0))); } -static void eval_round_to(TinyBlocks_Block* self, TinyBlocks* rt) { - out_num(self, tb_number_round_to(N(0), (int)N(1))); + +static void eval_pure(TinyBlocks_Block* self, TinyBlocks* rt) { + double x[4] = {0}; + uint32_t n = self->type->pure_arity; + for (uint32_t i = 0; i < n && i < 4; i++) x[i] = N(i); + out_num(self, self->type->pure_num(x)); } -static void eval_sin(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(sin(N(0) * DEG))); } -static void eval_cos(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(cos(N(0) * DEG))); } -static void eval_tan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(tan(N(0) * DEG))); } -static void eval_asin(TinyBlocks_Block* self, TinyBlocks* rt) { - double x = N(0); - out_num(self, (x < -1 || x > 1) ? 0.0 : trig(asin(x) / DEG)); -} -static void eval_acos(TinyBlocks_Block* self, TinyBlocks* rt) { - double x = N(0); - out_num(self, (x < -1 || x > 1) ? 0.0 : trig(acos(x) / DEG)); -} -static void eval_atan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(atan(N(0)) / DEG)); } -static void eval_log10(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log10(x) : 0.0); } -static void eval_ln(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log(x) : 0.0); } -static void eval_exp(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, exp(N(0))); } -static void eval_pi(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, M_PI); } static void eval_random(TinyBlocks_Block* self, TinyBlocks* rt) { double a = N(0), b = N(1); @@ -121,12 +124,6 @@ static void eval_random(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; } -static void eval_clamp(TinyBlocks_Block* self, TinyBlocks* rt) { - double x = N(0), lo = N(1), hi = N(2); - if (lo > hi) { double t = lo; lo = hi; hi = t; } - out_num(self, x < lo ? lo : x > hi ? hi : x); -} - static void eval_format(TinyBlocks_Block* self, TinyBlocks* rt) { char buf[64]; tb_number_format(N(0), (int)N(1), buf, sizeof(buf)); @@ -203,6 +200,16 @@ static void eval_from_base(TinyBlocks_Block* self, TinyBlocks* rt) { /* -- Registro --- */ +static const TinyBlocks_SlotDesc s_num_out[] = {{"numero", TB_VALUE_NONE}}; + +static bool pure(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, double (*f)(const double*)) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, s_num_out, 1, eval_pure); + if (!t) return false; + tb_type_block_set_pure(t, TB_PURE_NUM, f, ni); + return tb_library_add(lib, &t->base); +} + static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, const TinyBlocks_SlotDesc* in, uint32_t ni, const TinyBlocks_SlotDesc* out, uint32_t no, @@ -220,25 +227,25 @@ static bool number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { }; tb_library_set_category(lib, &cat); - TB_BLOCK_META("Number.Div", "eval_div", "Divisao com casas decimais (por 0 da 0)"); - TB_BLOCK_META("Number.Pow", "eval_pow", "A elevado a B"); - TB_BLOCK_META("Number.Sqrt", "eval_sqrt", "Raiz quadrada"); - TB_BLOCK_META("Number.Round", "eval_round", "Arredonda para o inteiro mais proximo"); - TB_BLOCK_META("Number.Floor", "eval_floor", "Arredonda para baixo"); - TB_BLOCK_META("Number.Ceil", "eval_ceil", "Arredonda para cima"); + TB_BLOCK_META("Number.Div", "f_div", "Divisao com casas decimais (por 0 da 0)"); + TB_BLOCK_META("Number.Pow", "f_pow", "A elevado a B"); + TB_BLOCK_META("Number.Sqrt", "f_sqrt", "Raiz quadrada"); + TB_BLOCK_META("Number.Round", "f_round", "Arredonda para o inteiro mais proximo"); + TB_BLOCK_META("Number.Floor", "f_floor", "Arredonda para baixo"); + TB_BLOCK_META("Number.Ceil", "f_ceil", "Arredonda para cima"); TB_BLOCK_META("Number.RoundTo", "tb_number_round_to", "Arredonda mantendo N casas decimais"); - TB_BLOCK_META("Number.Sin", "eval_sin", "Seno (angulo em graus)"); - TB_BLOCK_META("Number.Cos", "eval_cos", "Cosseno (angulo em graus)"); - TB_BLOCK_META("Number.Tan", "eval_tan", "Tangente (angulo em graus)"); - TB_BLOCK_META("Number.Asin", "eval_asin", "Arco-seno, em graus"); - TB_BLOCK_META("Number.Acos", "eval_acos", "Arco-cosseno, em graus"); - TB_BLOCK_META("Number.Atan", "eval_atan", "Arco-tangente, em graus"); - TB_BLOCK_META("Number.Log10", "eval_log10", "Logaritmo na base 10"); - TB_BLOCK_META("Number.Ln", "eval_ln", "Logaritmo natural (base e)"); - TB_BLOCK_META("Number.Exp", "eval_exp", "e elevado a X"); - TB_BLOCK_META("Number.Pi", "eval_pi", "O numero pi (3,14159...)"); + TB_BLOCK_META("Number.Sin", "f_sin", "Seno (angulo em graus)"); + TB_BLOCK_META("Number.Cos", "f_cos", "Cosseno (angulo em graus)"); + TB_BLOCK_META("Number.Tan", "f_tan", "Tangente (angulo em graus)"); + TB_BLOCK_META("Number.Asin", "f_asin", "Arco-seno, em graus"); + TB_BLOCK_META("Number.Acos", "f_acos", "Arco-cosseno, em graus"); + TB_BLOCK_META("Number.Atan", "f_atan", "Arco-tangente, em graus"); + TB_BLOCK_META("Number.Log10", "f_log10", "Logaritmo na base 10"); + TB_BLOCK_META("Number.Ln", "f_ln", "Logaritmo natural (base e)"); + TB_BLOCK_META("Number.Exp", "f_exp", "e elevado a X"); + TB_BLOCK_META("Number.Pi", "f_pi", "O numero pi (3,14159...)"); TB_BLOCK_META("Number.Random", "eval_random", "Numero real aleatorio entre A e B"); - TB_BLOCK_META("Number.Clamp", "eval_clamp", "Prende o numero entre o minimo e o maximo"); + TB_BLOCK_META("Number.Clamp", "f_clamp", "Prende o numero entre o minimo e o maximo"); TB_BLOCK_META("Number.Format", "tb_number_format", "Texto do numero com N casas decimais"); TB_BLOCK_META("Number.IsEven", "eval_is_even", "Verdadeiro se o numero for par"); TB_BLOCK_META("Number.IsPrime", "tb_number_is_prime", "Verdadeiro se o numero for primo"); @@ -262,25 +269,25 @@ static bool number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_SlotDesc prime_out[] = {{"é primo?", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc int_out[] = {{"é inteiro?", TB_VALUE_INTEGER}}; - return reg(rt, lib, "Number.Div", n2, 2, out, 1, eval_div) - && reg(rt, lib, "Number.Pow", n2, 2, out, 1, eval_pow) - && reg(rt, lib, "Number.Sqrt", n1, 1, out, 1, eval_sqrt) - && reg(rt, lib, "Number.Round", n1, 1, out, 1, eval_round) - && reg(rt, lib, "Number.Floor", n1, 1, out, 1, eval_floor) - && reg(rt, lib, "Number.Ceil", n1, 1, out, 1, eval_ceil) - && reg(rt, lib, "Number.RoundTo", nk, 2, out, 1, eval_round_to) - && reg(rt, lib, "Number.Sin", n1, 1, out, 1, eval_sin) - && reg(rt, lib, "Number.Cos", n1, 1, out, 1, eval_cos) - && reg(rt, lib, "Number.Tan", n1, 1, out, 1, eval_tan) - && reg(rt, lib, "Number.Asin", n1, 1, out, 1, eval_asin) - && reg(rt, lib, "Number.Acos", n1, 1, out, 1, eval_acos) - && reg(rt, lib, "Number.Atan", n1, 1, out, 1, eval_atan) - && reg(rt, lib, "Number.Log10", n1, 1, out, 1, eval_log10) - && reg(rt, lib, "Number.Ln", n1, 1, out, 1, eval_ln) - && reg(rt, lib, "Number.Exp", n1, 1, out, 1, eval_exp) - && reg(rt, lib, "Number.Pi", NULL, 0, out, 1, eval_pi) + return pure(rt, lib, "Number.Div", n2, 2, f_div) + && pure(rt, lib, "Number.Pow", n2, 2, f_pow) + && pure(rt, lib, "Number.Sqrt", n1, 1, f_sqrt) + && pure(rt, lib, "Number.Round", n1, 1, f_round) + && pure(rt, lib, "Number.Floor", n1, 1, f_floor) + && pure(rt, lib, "Number.Ceil", n1, 1, f_ceil) + && pure(rt, lib, "Number.RoundTo", nk, 2, f_round_to) + && pure(rt, lib, "Number.Sin", n1, 1, f_sin) + && pure(rt, lib, "Number.Cos", n1, 1, f_cos) + && pure(rt, lib, "Number.Tan", n1, 1, f_tan) + && pure(rt, lib, "Number.Asin", n1, 1, f_asin) + && pure(rt, lib, "Number.Acos", n1, 1, f_acos) + && pure(rt, lib, "Number.Atan", n1, 1, f_atan) + && pure(rt, lib, "Number.Log10", n1, 1, f_log10) + && pure(rt, lib, "Number.Ln", n1, 1, f_ln) + && pure(rt, lib, "Number.Exp", n1, 1, f_exp) + && pure(rt, lib, "Number.Pi", NULL, 0, f_pi) && reg(rt, lib, "Number.Random", n2, 2, out, 1, eval_random) - && reg(rt, lib, "Number.Clamp", n3, 3, out, 1, eval_clamp) + && pure(rt, lib, "Number.Clamp", n3, 3, f_clamp) && reg(rt, lib, "Number.Format", nk, 2, text_out, 1, eval_format) && reg(rt, lib, "Number.IsEven", n1, 1, even_out, 1, eval_is_even) && reg(rt, lib, "Number.IsPrime", n1, 1, prime_out, 1, eval_is_prime) diff --git a/libraries/tinyblocks-operators/src/tb_operators.c b/libraries/tinyblocks-operators/src/tb_operators.c index b6b6211..60585f1 100644 --- a/libraries/tinyblocks-operators/src/tb_operators.c +++ b/libraries/tinyblocks-operators/src/tb_operators.c @@ -8,6 +8,7 @@ #include #include #include +#include #include #include "tb_operators.h" @@ -15,9 +16,10 @@ +/* Texto sem diferenciar maiusculas (ASCII), como o "=" do Scratch */ static int str_icmp(const char* a, const char* b) { for (;; a++, b++) { - int ca = (*a | 32), cb = (*b | 32); + int ca = tolower((unsigned char)*a), cb = tolower((unsigned char)*b); if (ca != cb || !ca) return (ca > cb) - (ca < cb); } } @@ -74,60 +76,38 @@ static void eval_op_random(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; } -/* == Aritmética === */ -/* Inteiro com inteiro dá inteiro (conta exata); se um lado tiver casas +/* == Aritmética === + * Inteiro com inteiro dá inteiro (conta exata); se um lado tiver casas * decimais, a conta é real, como no Scratch: (134) * (0.8) = 107.2. - * O campo digitado chega como real (slot REAL), então 7 vale como inteiro. */ -typedef struct { bool ints; int64_t ia, ib; double a, b; } Num2; - + * Cada bloco é a função de doubles (TB_PURE_NUM): o eval e um executor que + * compile o bloco usam a mesma. */ static bool integral(double x) { return isfinite(x) && x == floor(x) && fabs(x) < 9e15; } -static Num2 num2(TinyBlocks_Block* s, TinyBlocks* rt, uint32_t n) { - Num2 r = { true, 0, 0, 0, 0 }; - r.a = tb_block_input_number(s, rt, 0, 0); - r.b = n > 1 ? tb_block_input_number(s, rt, 1, 0) : 0; - r.ints = integral(r.a) && integral(r.b); - r.ia = r.ints ? (int64_t)r.a : 0; - r.ib = r.ints ? (int64_t)r.b : 0; - return r; +static double f_add(const double* x) { return x[0] + x[1]; } +static double f_sub(const double* x) { return x[0] - x[1]; } +static double f_mul(const double* x) { return x[0] * x[1]; } +/* inteiros: divisão inteira; com real: divisão real (por 0 dá 0) */ +static double f_div(const double* x) { + if (integral(x[0]) && integral(x[1])) + return x[1] != 0.0 ? (double)((int64_t)x[0] / (int64_t)x[1]) : 0.0; + return x[1] != 0.0 ? x[0] / x[1] : 0.0; } -static void out_real(TinyBlocks_Block* s, double x) { - tb_block_set_output(s, 0, tb_value_real(isfinite(x) ? x : 0.0)); +static double f_mod(const double* x) { + if (integral(x[0]) && integral(x[1])) + return x[1] != 0.0 ? (double)((int64_t)x[0] % (int64_t)x[1]) : 0.0; + return x[1] != 0.0 ? fmod(x[0], x[1]) : 0.0; } -static void eval_add(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ia + n.ib)); else out_real(s, n.a + n.b); -} -static void eval_sub(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ia - n.ib)); else out_real(s, n.a - n.b); -} -static void eval_mul(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ia * n.ib)); else out_real(s, n.a * n.b); -} -/* inteiros: divisão inteira (como antes); com real: divisão real */ -static void eval_div(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ib ? n.ia / n.ib : 0)); - else out_real(s, n.b != 0.0 ? n.a / n.b : 0.0); -} -static void eval_mod(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ib ? n.ia % n.ib : 0)); - else out_real(s, n.b != 0.0 ? fmod(n.a, n.b) : 0.0); -} -static void eval_abs(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 1); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ia < 0 ? -n.ia : n.ia)); else out_real(s, fabs(n.a)); -} -static void eval_max(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ia > n.ib ? n.ia : n.ib)); else out_real(s, n.a > n.b ? n.a : n.b); -} -static void eval_min(TinyBlocks_Block* s, TinyBlocks* rt) { - Num2 n = num2(s, rt, 2); - if (n.ints) tb_block_set_output(s, 0, tb_value_integer(n.ia < n.ib ? n.ia : n.ib)); else out_real(s, n.a < n.b ? n.a : n.b); +static double f_abs(const double* x) { return fabs(x[0]); } +static double f_max(const double* x) { return x[0] > x[1] ? x[0] : x[1]; } +static double f_min(const double* x) { return x[0] < x[1] ? x[0] : x[1]; } + +static void eval_pure(TinyBlocks_Block* s, TinyBlocks* rt) { + double x[2] = {0, 0}; + for (uint32_t i = 0; i < s->type->pure_arity && i < 2; i++) x[i] = tb_block_input_number(s, rt, i, 0); + double r = s->type->pure_num(x); + if (integral(r)) tb_block_set_output(s, 0, tb_value_integer((int64_t)r)); + else tb_block_set_output(s, 0, tb_value_real(isfinite(r) ? r : 0.0)); + s->dirty = false; } /* == Texto === */ @@ -169,6 +149,26 @@ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, return t && tb_library_add(lib, &t->base); } +static bool pure(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, double (*f)(const double*)) { + static const TinyBlocks_SlotDesc out[] = {{"result", TB_VALUE_NONE}}; + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, 1, eval_pure); + if (!t) return false; + tb_type_block_set_pure(t, TB_PURE_NUM, f, ni); + return tb_library_add(lib, &t->base); +} + +/* Registra e declara a semantica pura (comparacoes e logica) */ +static bool reg_p(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, + const TinyBlocks_SlotDesc* out, uint32_t no, + void (*fn)(TinyBlocks_Block*, TinyBlocks*), int pure_kind) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); + if (!t) return false; + tb_type_block_set_pure(t, pure_kind, NULL, ni); + return tb_library_add(lib, &t->base); +} + static bool operators_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { srand((unsigned)time(NULL)); static const TinyBlocks_Category cat = { @@ -193,21 +193,21 @@ static bool operators_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { "Inverte o valor logico"); TB_BLOCK_META("Operators.Random", "eval_op_random", "Numero inteiro aleatorio entre A e B"); - TB_BLOCK_META("Math.Add", "eval_add", + TB_BLOCK_META("Math.Add", "f_add", "Soma dois numeros"); - TB_BLOCK_META("Math.Sub", "eval_sub", + TB_BLOCK_META("Math.Sub", "f_sub", "Subtrai B de A"); - TB_BLOCK_META("Math.Mul", "eval_mul", + TB_BLOCK_META("Math.Mul", "f_mul", "Multiplica dois numeros"); - TB_BLOCK_META("Math.Div", "eval_div", + TB_BLOCK_META("Math.Div", "f_div", "Divide A por B"); - TB_BLOCK_META("Math.Mod", "eval_mod", + TB_BLOCK_META("Math.Mod", "f_mod", "Resto da divisao de A por B"); - TB_BLOCK_META("Math.Abs", "eval_abs", + TB_BLOCK_META("Math.Abs", "f_abs", "Valor absoluto de um numero"); - TB_BLOCK_META("Math.Max", "eval_max", + TB_BLOCK_META("Math.Max", "f_max", "Maior entre dois numeros"); - TB_BLOCK_META("Math.Min", "eval_min", + TB_BLOCK_META("Math.Min", "f_min", "Menor entre dois numeros"); TB_BLOCK_META("Text.Concat", "eval_concat", "Junta dois textos"); @@ -241,21 +241,21 @@ static bool operators_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_SlotDesc lit_txt_in[] = {{"value", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc lit_txt_out[] = {{"out", TB_VALUE_TEXT}}; - if (!(reg(rt, lib, "Operators.Lt", any2, 2, bool_out, 1, eval_op_lt) - && reg(rt, lib, "Operators.Eq", any2, 2, bool_out, 1, eval_op_eq) - && reg(rt, lib, "Operators.Gt", any2, 2, bool_out, 1, eval_op_gt) - && reg(rt, lib, "Operators.And", bool2, 2, bool_out, 1, eval_op_and) - && reg(rt, lib, "Operators.Or", bool2, 2, bool_out, 1, eval_op_or) - && reg(rt, lib, "Operators.Not", bool1, 1, bool_out, 1, eval_op_not) + if (!(reg_p(rt, lib, "Operators.Lt", any2, 2, bool_out, 1, eval_op_lt, TB_PURE_LT) + && reg_p(rt, lib, "Operators.Eq", any2, 2, bool_out, 1, eval_op_eq, TB_PURE_EQ) + && reg_p(rt, lib, "Operators.Gt", any2, 2, bool_out, 1, eval_op_gt, TB_PURE_GT) + && reg_p(rt, lib, "Operators.And", bool2, 2, bool_out, 1, eval_op_and, TB_PURE_AND) + && reg_p(rt, lib, "Operators.Or", bool2, 2, bool_out, 1, eval_op_or, TB_PURE_OR) + && reg_p(rt, lib, "Operators.Not", bool1, 1, bool_out, 1, eval_op_not, TB_PURE_NOT) && reg(rt, lib, "Operators.Random", rnd_in, 2, any_out, 1, eval_op_random) - && reg(rt, lib, "Math.Add", two_int, 2, int_out, 1, eval_add) - && reg(rt, lib, "Math.Sub", two_int, 2, int_out, 1, eval_sub) - && reg(rt, lib, "Math.Mul", two_int, 2, int_out, 1, eval_mul) - && reg(rt, lib, "Math.Div", two_int, 2, int_out, 1, eval_div) - && reg(rt, lib, "Math.Mod", two_int, 2, int_out, 1, eval_mod) - && reg(rt, lib, "Math.Abs", one_int, 1, int_out, 1, eval_abs) - && reg(rt, lib, "Math.Max", two_int, 2, int_out, 1, eval_max) - && reg(rt, lib, "Math.Min", two_int, 2, int_out, 1, eval_min) + && pure(rt, lib, "Math.Add", two_int, 2, f_add) + && pure(rt, lib, "Math.Sub", two_int, 2, f_sub) + && pure(rt, lib, "Math.Mul", two_int, 2, f_mul) + && pure(rt, lib, "Math.Div", two_int, 2, f_div) + && pure(rt, lib, "Math.Mod", two_int, 2, f_mod) + && pure(rt, lib, "Math.Abs", one_int, 1, f_abs) + && pure(rt, lib, "Math.Max", two_int, 2, f_max) + && pure(rt, lib, "Math.Min", two_int, 2, f_min) && reg(rt, lib, "Text.Concat", two_text, 2, text_out, 1, eval_concat) && reg(rt, lib, "Text.Length", text_in, 1, int_out, 1, eval_len) && reg(rt, lib, "Literal.Integer", lit_int_in, 1, lit_int_out, 1, eval_lit_int) diff --git a/src/tb_type_block.c b/src/tb_type_block.c index 30fd84d..8583bd9 100644 --- a/src/tb_type_block.c +++ b/src/tb_type_block.c @@ -74,6 +74,14 @@ void tb_type_block_set_label(TinyBlocks_TypeBlock* tb, const char* label, const tb->label_defaults = defaults; } +void tb_type_block_set_pure(TinyBlocks_TypeBlock* tb, int pure, double (*num)(const double* x), uint32_t arity) +{ + if (!tb) return; + tb->pure = pure; + tb->pure_num = num; + tb->pure_arity = arity; +} + void tb_type_block_set_input_flags(TinyBlocks_TypeBlock* tb, uint32_t i, uint32_t flags) { if (tb && tb->input_flags && i < tb->input_desc_count) tb->input_flags[i] = flags; } void tb_type_block_set_output_flags(TinyBlocks_TypeBlock* tb, uint32_t i, uint32_t flags) diff --git a/tests/editor_harness.c b/tests/editor_harness.c index a9ff6ed..ca72c26 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -15,6 +15,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -287,6 +290,9 @@ int main(void) { tb_library_register(rt, tb_control_get_library()); tb_library_register(rt, tb_errors_get_library()); tb_library_register(rt, tb_operators_get_library()); + tb_library_register(rt, tb_number_get_library()); + tb_library_register(rt, tb_string_get_library()); + tb_library_register(rt, tb_vector_get_library()); tb_library_register(rt, tb_variables_get_library()); tb_library_register(rt, tb_appearance_get_library()); tb_library_register(rt, tb_pen_get_library()); @@ -1391,6 +1397,35 @@ int main(void) { remove(bigp2); } + /* 30. Expressoes compiladas (tb_editor_jit.c): mesma saida que no por no */ + { + bool err = false; + char* t = mcp("new_tab", "{\"name\":\"Contas\"}", &err, NULL); + free(t); + t = mcp("add_scratchblocks", "{\"code\":\"when flag clicked\\n" + "set [t v] to [abc]\\nset [n v] to (7)\\n" + "delete all of [L v]\\nadd (1) to [L v]\\nadd (5) to [L v]\\n" + "say (join [a=] ((n) / (2)))\\n" + "say (join [b=] (((n) - (1)) * (0.5)))\\n" + "say (join [c=] ((t) + (1)))\\n" + "say (join [d=] ((item (2) of [L v]) * (10)))\\n" + "if <<(t) = [ABC]> and >> then\\nsay [e=sim]\\nend\\n" + "if <[abd] > (t)> then\\nsay [f=sim]\\nend\\n" + "say (join [g=] ((n) * (n)))\\n\",\"x\":40,\"y\":40}", &err, NULL); + CHECK(!err, "contas: cria o script"); + free(t); + flag(); + for (int i = 0; i < 3; i++) frame(0, 0, 0, 0, 0, 0, NULL); + CHECK(console_has("a=3.5"), "compilado: (7) / (2) = 3.5"); + CHECK(console_has("b=3"), "compilado: ((7) - (1)) * (0.5) = 3"); + CHECK(console_has("c=1"), "compilado: texto numa conta vale 0"); + CHECK(console_has("d=50"), "compilado: item de lista (não compilado) dentro da conta"); + CHECK(console_has("e=sim"), "compilado: = compara texto sem maiúsculas; não; e"); + CHECK(console_has("f=sim"), "compilado: > entre textos compara o texto"); + CHECK(console_has("g=49"), "compilado: inteiro * inteiro"); + stop(); + } + tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); return fails != 0; diff --git a/tests/meta_test.c b/tests/meta_test.c index e62f865..5172dc5 100644 --- a/tests/meta_test.c +++ b/tests/meta_test.c @@ -19,7 +19,7 @@ int main(void) { const TinyBlocks_BlockMeta* m = tb_meta_find("Math.Add"); CHECK(m != NULL, "acha Math.Add"); if (m) { - CHECK(m->func_name && !strcmp(m->func_name, "eval_add"), "funcao = eval_add"); + CHECK(m->func_name && !strcmp(m->func_name, "f_add"), "funcao = f_add (a conta pura do bloco)"); CHECK(m->doc && strstr(m->doc, "Soma"), "doc menciona 'Soma'"); CHECK(m->file && strstr(m->file, "tb_operators.c"), "arquivo tb_operators.c"); } @@ -35,11 +35,11 @@ int main(void) { char path[1200]; CHECK(tb_meta_resolve_file(m->file, path, sizeof(path)), "resolve o arquivo-fonte"); int line = tb_meta_line(m); - CHECK(line > 0, "localiza a linha de eval_add"); + CHECK(line > 0, "localiza a linha de f_add"); if (line > 0) { char buf[1024]; int got = tb_meta_read_lines(m, line, 1, buf, sizeof(buf)); - CHECK(got == 1 && strstr(buf, "eval_add"), "le a linha da funcao"); + CHECK(got == 1 && strstr(buf, "f_add"), "le a linha da funcao"); } } diff --git a/tests/stdlib_test.c b/tests/stdlib_test.c index 9419fce..2851d81 100644 --- a/tests/stdlib_test.c +++ b/tests/stdlib_test.c @@ -102,6 +102,8 @@ int main(void) { CHECK(is_real(run("Math.Add", "0.4", "1", NULL), 1.4), "(0.4) + (1) = 1.4"); CHECK(is_real(run("Math.Sub", "-5", "0.25", NULL), -5.25), "(-5) - (0.25) = -5.25"); CHECK(is_int(run("Math.Mul", "6", "7", NULL), 42), "inteiro * inteiro continua inteiro"); + CHECK(is_int(run("Operators.Eq", "abc", "ABC", NULL), 1), "= entre textos ignora maiúsculas (abc = ABC)"); + CHECK(is_int(run("Operators.Gt", "abd", "abc", NULL), 1), "> entre textos"); CHECK(is_int(run("Math.Div", "7", "2", NULL), 3), "Math.Div de inteiros continua divisão inteira"); CHECK(is_real(run("Math.Div", "7.5", "2", NULL), 3.75), "Math.Div com real é real"); CHECK(is_real(run("Math.Max", "0.5", "0.2", NULL), 0.5) && is_real(run("Math.Abs", "-2.5", NULL, NULL), 2.5), diff --git a/tests/vm_bench.c b/tests/vm_bench.c new file mode 100644 index 0000000..edee75a --- /dev/null +++ b/tests/vm_bench.c @@ -0,0 +1,127 @@ +#define _POSIX_C_SOURCE 200809L +/* vm_bench.c - mede a VM do editor rodando um projeto sem janela. + * Uso: build/vm_bench projeto.json [quadros] + * Clica a bandeira e, a cada quadro do editor, liga a variavel "mudou" + * (o Minecraft so redesenha quando a camera mexe) e mede o tempo do quadro. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static TinyBlocks* rt; +static TinyBlocks_Block *ev, *scene; + +static double now(void); +static double t_eval, t_draw; +static void frame(void) { + tb_block_set_output(ev, GFX_IN_WIN_W, tb_value_integer(1280)); + tb_block_set_output(ev, GFX_IN_WIN_H, tb_value_integer(720)); + tb_block_set_output(ev, GFX_IN_TEXT, tb_value_text("")); + tb_block_set_output(ev, GFX_IN_DROP_FILE, tb_value_text("")); + double a = now(); + tb_block_eval(scene, rt); + double b = now(); + TinyBlocks_RenderableBlock* rb = NULL; + scene->type->on_draw(scene, rt, &rb); + t_eval += b - a; t_draw += now() - b; + tb_renderable_release_all(); +} + +static double now(void) { + struct timespec t; + clock_gettime(CLOCK_MONOTONIC, &t); + return t.tv_sec + t.tv_nsec / 1e9; +} + +int main(int argc, char** argv) { + if (argc < 2) { fprintf(stderr, "uso: %s projeto.json [quadros]\n", argv[0]); return 2; } + int frames = argc > 2 ? atoi(argv[2]) : 20; + setenv("XDG_CONFIG_HOME", "/tmp/tb_bench_cfg", 1); + setenv("TINYBLOCKS_MCP_PORT", "0", 1); + tinyblocks_init(&rt, NULL); + tb_graphics_set_backend(tb_graphics_null_backend()); + tb_library_register(rt, tb_events_get_library()); + tb_library_register(rt, tb_control_get_library()); + tb_library_register(rt, tb_errors_get_library()); + tb_library_register(rt, tb_operators_get_library()); + tb_library_register(rt, tb_variables_get_library()); + tb_library_register(rt, tb_appearance_get_library()); + tb_library_register(rt, tb_pen_get_library()); + tb_library_register(rt, tb_input_get_library()); + tb_library_register(rt, tb_imglib_get_library()); + tb_library_register(rt, tb_number_get_library()); + tb_library_register(rt, tb_string_get_library()); + tb_library_register(rt, tb_vector_get_library()); + tb_library_register(rt, tb_graphics_get_library()); + tb_library_register(rt, tb_editor_get_library()); + ev = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Input")); + scene = tb_block_create(rt, tb_type_block_find(rt, "Editor.Scene")); + tb_block_set_default(scene, 0, tb_value_block(ev)); + frame(); + Ed* ed = *(Ed**)scene->userdata; + if (!project_load(ed, argv[1])) { fprintf(stderr, "nao abriu: %s\n", ed->hot_status); return 1; } + tab_select(ed, ed->tab_n - 1); /* a ultima aba (o programa) */ + frame(); + run_flag(ed); + /* quadros do editor ate o primeiro desenho completo (setup + 1o render) */ + if (getenv("BENCH_PROFILE")) { /* so render: "mudou" sempre ligado */ + for (int k = 0; k < frames; k++) { tb_vars_set("mudou", tb_value_integer(1)); frame(); } + return 0; + } + double t0 = now(); + int n = 0; + while (ed->vm_running && n < 100000) { frame(); n++; const TinyBlocks_Value* m = tb_vars_get("nf"); if (m && n > 2 && tb_vars_get("mudou") && tb_vars_get("mudou")->as.integer == 0 && tb_vars_get("f") && tb_value_as_number(*tb_vars_get("f"), 0) >= tb_value_as_number(*m, 0)) break; } + printf("setup + 1o quadro: %.3f s (%d quadros do editor)\n", now() - t0, n); + double best = 1e9, sum = 0; + for (int k = 0; k < frames; k++) { + tb_vars_set("mudou", tb_value_integer(1)); + tb_vars_set("yaw", tb_value_integer(k * 3)); + double a = now(); + t_eval = t_draw = 0; + int m = 0; + do { frame(); m++; } while (tb_vars_get("mudou")->as.integer == 1 || tb_value_as_number(*tb_vars_get("f"), 0) < tb_value_as_number(*tb_vars_get("nf"), 0)); + /* o render termina quando f chega em nf de novo */ + double dt = now() - a; + sum += dt; if (dt < best) best = dt; + printf("render %2d: %.1f ms (%d quadros do editor; VM+entrada %.1f ms, desenho %.1f ms = %.1f ms/quadro)\n", + k, dt * 1000, m, t_eval * 1000, t_draw * 1000, t_draw * 1000 / m); + } + const char* show[] = { "nf", "f", "tela", "x0", "pyy", "ok", "vis" }; + for (int i = 0; i < 7; i++) { + const TinyBlocks_Value* v = tb_vars_get(show[i]); + char buf[64] = "(nao existe)"; + if (v) tb_value_to_text(*v, buf, sizeof(buf)); + printf(" %s = %s\n", show[i], buf); + } + const TinyBlocks_Value* tv = tb_vars_get("tela"); + if (tv && tv->kind == TB_VALUE_IMAGE) { /* checksum da tela (FNV-1a) */ + const TinyBlocks_Image* im = tv->as.image; + const uint8_t* d = tb_image_data_const(im); + size_t n = (size_t)tb_image_width(im) * tb_image_height(im) * tb_image_channels(im); + uint32_t h = 2166136261u; + for (size_t i = 0; i < n; i++) { h ^= d[i]; h *= 16777619u; } + printf(" checksum da tela: %08x\n", h); + } + printf("media %.1f ms, melhor %.1f ms\n", sum / frames * 1000, best * 1000); + return 0; +}