From b4a27f01804dcdf60601e5a96898ecc10bd886ea Mon Sep 17 00:00:00 2001 From: mguinhos Date: Fri, 23 Oct 2026 17:18:08 -0300 Subject: [PATCH] =?UTF-8?q?Executor=20compila=20"mude=20para"=20e=20"mude?= =?UTF-8?q?=20por";=20listas=20e=20vari=C3=A1veis=20sem=20procurar=20nome?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TB_PURE_SET_VAR / TB_PURE_CHANGE_VAR: os comandos de variável rodam direto do programa compilado (alvo resolvido para o slot), sem montar, marcar e avaliar a árvore do bloco. - Condição compilada de "se"/"repita até" é lida sem set_output/cópia. - get_rt: o bloco guarda a própria árvore (rt_hot), sem busca no hash. - Listas com nome: o bloco guarda o índice da lista; antes copiava o nome com snprintf e procurava entre todas a cada acesso. - TbVarsEpoch: o código compilado guarda o ponteiro do valor da variável e só confere geração e escopo (sem chamada). Blocos de variável com o nome no próprio campo pulam o strcmp de conferência. - jcmp compara números sem passar por TinyBlocks_Value. Minecraft, vista de perto: pior 19 ms -> 10 ms; 748 M -> 565 M instruções em 3 renders. Mesma imagem (checksum) com e sem compilador. Co-Authored-By: Claude Opus 5.5 --- include/tinyblocks/tb_type_block.h | 7 +- include/tinyblocks/tb_vars.h | 5 + .../include/tb_editor_internal.h | 19 ++ libraries/tinyblocks-editor/src/tb_editor.c | 23 ++- .../tinyblocks-editor/src/tb_editor_jit.c | 191 ++++++++++++++++-- .../tinyblocks-variables/src/tb_variables.c | 8 +- libraries/tinyblocks-vector/src/tb_vector.c | 41 ++-- src/tb_vars.c | 12 +- tests/editor_harness.c | 6 +- tests/vm_bench.c | 22 +- 10 files changed, 294 insertions(+), 40 deletions(-) diff --git a/include/tinyblocks/tb_type_block.h b/include/tinyblocks/tb_type_block.h index bd8ef6e..f9752f2 100644 --- a/include/tinyblocks/tb_type_block.h +++ b/include/tinyblocks/tb_type_block.h @@ -100,13 +100,18 @@ struct TinyBlocks_TypeBlock { * 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). */ + * VAR: o valor da variavel com o nome da entrada 0 (sem variavel = 0). + * Comandos (sem saida), efeito so na variavel com o nome da entrada 0: + * SET_VAR: passa a valer a entrada 1 (copia), criada global se nao existir. + * CHANGE_VAR: soma o numero da entrada 1 ao numero dela; inteiro se as + * duas parcelas forem inteiras, senao real. */ 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, + TB_PURE_SET_VAR, TB_PURE_CHANGE_VAR, }; /* -- Forma e tracos --- */ diff --git a/include/tinyblocks/tb_vars.h b/include/tinyblocks/tb_vars.h index 53487b2..0672017 100644 --- a/include/tinyblocks/tb_vars.h +++ b/include/tinyblocks/tb_vars.h @@ -46,6 +46,11 @@ typedef struct { bool fixed; /* quem chama garante: o texto do nome nunca muda (pula o strcmp) */ } TbVarRef; TB_API const TinyBlocks_Value* tb_vars_get_ref(const char* name, TbVarRef* ref); +/* Estado que invalida as referencias (geracao + escopo atual), num endereco + * fixo: um ponteiro para o valor achado com tb_vars_get_ref continua valido + * enquanto gen e scope forem os mesmos de quando foi achado. */ +typedef struct { uint32_t gen; const void* scope; } TbVarsEpoch; +TB_API const TbVarsEpoch* tb_vars_epoch(void); TB_API void tb_vars_set_ref(const char* name, TinyBlocks_Value v, TbVarRef* ref); /* -- Globais (monitores, salvar projeto) -- */ diff --git a/libraries/tinyblocks-editor/include/tb_editor_internal.h b/libraries/tinyblocks-editor/include/tb_editor_internal.h index 9346a18..1ea8c18 100644 --- a/libraries/tinyblocks-editor/include/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/include/tb_editor_internal.h @@ -559,6 +559,17 @@ typedef struct { Part parts[MAX_PARTS]; TinyBlocks_Block* live_rt; /* última instância no runtime (não-owning) */ + /* atalho do get_rt: a arvore deste bloco no cache do runtime (vale com a + mesma geracao do cache, aba, indice e profundidade de chamada) */ + TinyBlocks_Block* rt_hot; + const void* rt_hot_T; + int rt_hot_bi, rt_hot_depth; + uint32_t rt_hot_gen; + /* comando compilado (tb_editor_jit.c), com a mesma chave do rt_hot */ + void* jst; + const void* jst_T; + int jst_bi, jst_depth; + uint32_t jst_gen; } EdBlock; /* Um trecho colorido do editor de codigo (vindo do tinyblocks-syntax). */ @@ -870,6 +881,9 @@ typedef struct Ed { int vm_var_n; /* variaveis conhecidas (refaz a paleta) */ RtCacheEnt rt_cache[RT_CACHE_CAP]; int rt_cache_n; + uint32_t rt_gen; /* muda quando o cache e esvaziado (EdBlock.rt_hot) */ + void** jit_list; /* comandos compilados (liberados com o cache) */ + int jit_n, jit_cap; int run_n, run_cap; Tab* live_tab; FILE* cap_file; @@ -1081,6 +1095,11 @@ 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); +/* Roda o comando bi compilado (TB_PURE_SET_VAR/CHANGE_VAR); false = nao compila */ +bool jit_stmt(Ed* ed, Tab* T, int bi, TinyBlocks_TypeBlock* t); +void jit_reset(Ed* ed); /* esquece os comandos compilados */ +bool jit_is_compiled(const TinyBlocks_Block* r); +TinyBlocks_Value jit_block_value(TinyBlocks_Block* r); /* numero, sem copia */ 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 6cf5f5c..94efb7e 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -514,7 +514,7 @@ static int copy_tree(Tab* S, int si, Tab* D, bool with_next) { *n = *o; n->parent = -1; n->prel = REL_NONE; n->next = -1; n->sub[0] = n->sub[1] = n->sub[2] = -1; - n->live_rt = NULL; n->dragging = false; + n->live_rt = NULL; n->rt_hot = NULL; n->dragging = false; for (int s = 0; s < MAX_INPUTS; s++) n->args[s] = -1; for (int s = 0; s < MAX_INPUTS; s++) { if (o->args[s] < 0) continue; @@ -1254,6 +1254,8 @@ static void run_reset(Ed* ed) { ed->vm_n = 0; ed->vm_running = false; ed->rt_cache_n = 0; + ed->rt_gen++; + jit_reset(ed); memset(ed->rt_cache, 0, sizeof(ed->rt_cache)); for (int i = ed->run_n - 1; i >= 0; i--) tb_block_destroy(ed->run_blocks[i], ed->rt); ed->run_n = 0; @@ -1282,7 +1284,7 @@ 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 */ + if (t->pure >= TB_PURE_NUM && t->pure <= TB_PURE_NOT) { /* expressao pura: compila */ TinyBlocks_Block* c = jit_build(ed, T, bi); if (c) return c; } @@ -1313,8 +1315,10 @@ TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) { Chamado quando o usuario edita algo, para a edicao valer no programa que esta rodando. */ static void rt_cache_clear(Ed* ed) { - if (!ed->rt_cache_n) return; + if (!ed->rt_cache_n && !ed->jit_n) return; ed->rt_cache_n = 0; + ed->rt_gen++; + jit_reset(ed); memset(ed->rt_cache, 0, sizeof(ed->rt_cache)); } @@ -1331,6 +1335,12 @@ void rt_mark_dirty(TinyBlocks_Block* r, int depth) { uma recursao nao reusar uma arvore que ainda esta sendo avaliada). */ static TinyBlocks_Block* get_rt(Ed* ed, Tab* T, int bi) { int depth = ed->frame_n; + EdBlock* b = &T->ws[bi]; + if (b->rt_hot && b->rt_hot_gen == ed->rt_gen && b->rt_hot_T == T && b->rt_hot_bi == bi && + b->rt_hot_depth == depth) { + rt_mark_dirty(b->rt_hot, 0); + return b->rt_hot; + } uintptr_t h = ((uintptr_t)T >> 4) * 31u + (uintptr_t)bi * 131u + (uintptr_t)depth * 7u; for (int k = 0; k < RT_CACHE_CAP; k++) { RtCacheEnt* e = &ed->rt_cache[(h + (uintptr_t)k) % RT_CACHE_CAP]; @@ -1340,11 +1350,14 @@ static TinyBlocks_Block* get_rt(Ed* ed, Tab* T, int bi) { if (r && ed->rt_cache_n < RT_CACHE_CAP * 3 / 4) { e->T = T; e->bi = bi; e->depth = depth; e->r = r; ed->rt_cache_n++; + b = &T->ws[bi]; /* montar pode ter crescido o pool */ + b->rt_hot = r; b->rt_hot_T = T; b->rt_hot_bi = bi; b->rt_hot_depth = depth; b->rt_hot_gen = ed->rt_gen; } return r; } if (e->T == T && e->bi == bi && e->depth == depth) { rt_mark_dirty(e->r, 0); + b->rt_hot = e->r; b->rt_hot_T = T; b->rt_hot_bi = bi; b->rt_hot_depth = depth; b->rt_hot_gen = ed->rt_gen; return e->r; } } @@ -1355,6 +1368,7 @@ static TinyBlocks_Block* get_rt(Ed* ed, Tab* T, int bi) { static TinyBlocks_Value eval_reporter(Ed* ed, Tab* T, int bi) { TinyBlocks_Block* r = get_rt(ed, T, bi); if (!r) return tb_value_none(); + if (jit_is_compiled(r)) return jit_block_value(r); /* numero: sem avaliar/copiar */ tb_block_eval(r, ed->rt); return r->output_count > 0 ? tb_value_clone(r->outputs[0]) : tb_value_none(); } @@ -1482,6 +1496,7 @@ static bool vm_step(Ed* ed, VmThread* th, bool sync) { Shape sh = shape_of(t); if (sh == SH_HAT || shape_is_value(sh)) continue; if (t->flow) { vm_push(ed, th, T, bi, VF_FLOW); continue; } + if ((t->pure == TB_PURE_SET_VAR || t->pure == TB_PURE_CHANGE_VAR) && jit_stmt(ed, T, bi, t)) continue; TinyBlocks_Block* r = get_rt(ed, T, bi); if (r) tb_block_eval(r, ed->rt); if (t->flags & TB_TYPE_REDRAW) ed->redraw_req = true; /* caneta: mostra este quadro */ @@ -7679,6 +7694,8 @@ static void editor_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { free(ed->fdlg.ents); free(ed->sbp_text); free(ed->run_blocks); + jit_reset(ed); + free(ed->jit_list); free(ed->grp_mem); free(ed->grp_mem_pos); for (int u = 0; u < ed->user_block_n; u++) free(ed->user_blocks[u].snap); diff --git a/libraries/tinyblocks-editor/src/tb_editor_jit.c b/libraries/tinyblocks-editor/src/tb_editor_jit.c index d6d1165..5fd9f0f 100644 --- a/libraries/tinyblocks-editor/src/tb_editor_jit.c +++ b/libraries/tinyblocks-editor/src/tb_editor_jit.c @@ -36,11 +36,15 @@ typedef struct { TinyBlocks_Value cval; /* J_CONST: valor original (owned) */ TinyBlocks_Block* gen; /* J_GEN (dono: run_blocks do editor) */ TbVarRef ref; /* J_VAR */ + const TinyBlocks_Value* vp; /* J_VAR: valor achado, valido com vgen/vscope */ + uint32_t vgen; + const void* vscope; char name[64]; /* J_VAR */ } JNode; typedef struct { TinyBlocks* rt; + const TbVarsEpoch* ep; int n, root; JNode node[]; } JProg; @@ -137,6 +141,15 @@ static int compile_block(JCtx* c, int bi) { static double jnum(JProg* P, int i); +/* Valor da variavel: o ponteiro guardado vale enquanto ninguem criar/apagar + * variavel nem trocar de escopo (dois inteiros comparados, sem chamada) */ +static inline const TinyBlocks_Value* jvar(JProg* P, JNode* x) { + if (x->vp && x->vgen == P->ep->gen && x->vscope == P->ep->scope) return x->vp; + const TinyBlocks_Value* v = tb_vars_get_ref(x->name, &x->ref); + x->vp = v; x->vgen = P->ep->gen; x->vscope = P->ep->scope; + return v; +} + /* 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); @@ -150,7 +163,7 @@ static TinyBlocks_Value jval(JProg* P, int i, TinyBlocks_Value* tmp) { switch (x->op) { case J_CONST: return x->cval; case J_VAR: { - const TinyBlocks_Value* v = tb_vars_get_ref(x->name, &x->ref); + const TinyBlocks_Value* v = jvar(P, x); return v ? *v : tb_value_integer(0); } case J_GEN: return gen_eval(P, x); @@ -170,19 +183,44 @@ static int icmp(const char* a, const char* b) { } } +/* Numero do no, se for numero; senao o texto dele em txt (sem reavaliar) */ +static bool jnum_try(JProg* P, int i, double* d, char* txt, size_t cap) { + JNode* x = &P->node[i]; + TinyBlocks_Value v; + switch (x->op) { + case J_CONST: + if (x->k_num) { *d = x->k; return true; } + v = x->cval; + break; + case J_VAR: { + const TinyBlocks_Value* p = jvar(P, x); + if (!p) { *d = 0; return true; } /* sem variavel = 0 */ + if (p->kind == TB_VALUE_INTEGER) { *d = (double)p->as.integer; return true; } + if (p->kind == TB_VALUE_REAL) { *d = p->as.real; return true; } + v = *p; + break; + } + case J_GEN: v = gen_eval(P, x); break; + default: *d = jnum(P, i); return true; + } + if (tb_value_to_number(v, d)) return true; + tb_value_to_text(v, txt, cap); + return false; +} + +static void num_text(double d, char* txt, size_t cap) { + TinyBlocks_Value v = (d == floor(d) && fabs(d) < 9e15) ? tb_value_integer((int64_t)d) : tb_value_real(d); + tb_value_to_text(v, txt, cap); +} + 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); + char sa[256], sb[256]; + bool an = jnum_try(P, x->arg[0], &p, sa, sizeof(sa)); + bool bn = jnum_try(P, x->arg[1], &q, sb, sizeof(sb)); 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)); + if (an) num_text(p, sa, sizeof(sa)); + if (bn) num_text(q, sb, sizeof(sb)); return icmp(sa, sb); } @@ -200,7 +238,7 @@ static double jnum(JProg* P, int 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); + const TinyBlocks_Value* v = jvar(P, x); 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; @@ -223,14 +261,18 @@ static double jnum(JProg* P, int i) { return 0.0; } +/* Numero como valor: inteiro se der exato, senao real */ +static TinyBlocks_Value jit_num_value(double d) { + if (isfinite(d) && d == floor(d) && fabs(d) < 9e15) return tb_value_integer((int64_t)d); + return tb_value_real(isfinite(d) ? d : 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)); + tb_block_set_output(self, 0, jit_num_value(P ? jnum(P, P->root) : 0.0)); self->dirty = false; } @@ -268,6 +310,7 @@ TinyBlocks_Block* jit_build(Ed* ed, Tab* T, int bi) { JProg* P = r ? tb_alloc(ed->rt, sizeof(JProg) + (size_t)c->n * sizeof(JNode)) : NULL; if (P) { P->rt = ed->rt; + P->ep = tb_vars_epoch(); P->n = c->n; P->root = root; memcpy(P->node, c->node, (size_t)c->n * sizeof(JNode)); @@ -283,3 +326,121 @@ TinyBlocks_Block* jit_build(Ed* ed, Tab* T, int bi) { free(c); return r; } + +/* -- Valor de um bloco compilado, sem set_output/copia (condicoes) --- */ + +bool jit_is_compiled(const TinyBlocks_Block* r) { + return r && r->type && r->type->eval_fn == eval_compiled; +} + +TinyBlocks_Value jit_block_value(TinyBlocks_Block* r) { + JProg* P = r->userdata; + return jit_num_value(P ? jnum(P, P->root) : 0.0); +} + +/* -- Comandos compilados (TB_PURE_SET_VAR / TB_PURE_CHANGE_VAR) --- + * "mude [x] para (expr)" e "mude [x] por (expr)" rodam direto: o alvo e + * resolvido uma vez para o slot (TbVarRef com nome fixo) e o valor sai do + * programa compilado, sem montar/marcar/avaliar a arvore do bloco. */ + +typedef struct { + int pure; + char name[64]; + TbVarRef ref; + JProg* val; /* malloc; nos GEN sao da run_blocks */ +} JStmt; + +static char s_jit_none; /* "nao compila": nao tenta de novo */ +#define JIT_NONE ((void*)&s_jit_none) + +static void prog_free_consts(JProg* P) { + for (int i = 0; i < P->n; i++) + if (P->node[i].op == J_CONST) tb_value_free(&P->node[i].cval); +} + +/* Esquece os comandos compilados (o cache do runtime foi esvaziado) */ +void jit_reset(Ed* ed) { + for (int i = 0; i < ed->jit_n; i++) { + JStmt* S = ed->jit_list[i]; + prog_free_consts(S->val); + free(S->val); + free(S); + } + ed->jit_n = 0; +} + +static JStmt* stmt_compile(Ed* ed, Tab* T, int bi, TinyBlocks_TypeBlock* t) { + EdBlock* b = &T->ws[bi]; + if (t->input_desc_count < 2 || b->args[0] >= 0) return NULL; /* nome calculado */ + const char* nm = slot_src(b, 0); + if (!nm[0] || strlen(nm) >= sizeof(((JStmt*)0)->name)) return NULL; + if (ed->jit_n == ed->jit_cap) { + int nc = ed->jit_cap ? ed->jit_cap * 2 : 64; + void** nl = realloc(ed->jit_list, (size_t)nc * sizeof(void*)); + if (!nl) return NULL; + ed->jit_list = nl; ed->jit_cap = nc; + } + JCtx* c = calloc(1, sizeof(JCtx)); + if (!c) return NULL; + c->ed = ed; c->T = T; + int root = compile_slot(c, bi, 1); + JStmt* S = NULL; + if (!c->fail && root >= 0) { + S = calloc(1, sizeof(JStmt)); + JProg* P = S ? malloc(sizeof(JProg) + (size_t)c->n * sizeof(JNode)) : NULL; + if (P) { + P->rt = ed->rt; + P->ep = tb_vars_epoch(); + P->n = c->n; + P->root = root; + memcpy(P->node, c->node, (size_t)c->n * sizeof(JNode)); + c->n = 0; + S->val = P; + S->pure = t->pure; + strcpy(S->name, nm); + S->ref.fixed = true; + ed->jit_list[ed->jit_n++] = S; + } else { + free(S); + S = 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 S; +} + +static void stmt_run(JStmt* S) { + JProg* P = S->val; + JNode* x = &P->node[P->root]; + if (S->pure == TB_PURE_SET_VAR) { + TinyBlocks_Value tmp; + TinyBlocks_Value v = x->op == J_CONST || x->op == J_VAR || x->op == J_GEN + ? jval(P, P->root, &tmp) + : (tmp = jit_num_value(jnum(P, P->root))); + tb_vars_set_ref(S->name, v, &S->ref); + return; + } + double d = x->op == J_CONST ? x->k : jnum(P, P->root); + const TinyBlocks_Value* cur = tb_vars_get_ref(S->name, &S->ref); + double a = cur ? tb_value_as_number(*cur, 0) : 0; + TinyBlocks_Value nv = (a == floor(a) && d == floor(d)) + ? tb_value_integer((long long)llround(a + d)) + : tb_value_real(a + d); + tb_vars_set_ref(S->name, nv, &S->ref); +} + +bool jit_stmt(Ed* ed, Tab* T, int bi, TinyBlocks_TypeBlock* t) { + EdBlock* b = &T->ws[bi]; + int depth = ed->frame_n; + if (!(b->jst && b->jst_gen == ed->rt_gen && b->jst_T == T && b->jst_bi == bi && b->jst_depth == depth)) { + const char* off = getenv("TINYBLOCKS_NO_JIT"); + JStmt* S = (off && off[0] && off[0] != '0') ? NULL : stmt_compile(ed, T, bi, t); + b = &T->ws[bi]; + b->jst = S ? (void*)S : JIT_NONE; + b->jst_gen = ed->rt_gen; b->jst_T = T; b->jst_bi = bi; b->jst_depth = depth; + } + if (b->jst == JIT_NONE) return false; + stmt_run(b->jst); + return true; +} diff --git a/libraries/tinyblocks-variables/src/tb_variables.c b/libraries/tinyblocks-variables/src/tb_variables.c index 144e2ff..a0da8ba 100644 --- a/libraries/tinyblocks-variables/src/tb_variables.c +++ b/libraries/tinyblocks-variables/src/tb_variables.c @@ -22,7 +22,11 @@ static TbVarRef* ref_of(TinyBlocks_Block* self, TinyBlocks* rt) { if (!self->userdata) { self->userdata = tb_alloc(rt, sizeof(TbVarRef)); - if (self->userdata) memset(self->userdata, 0, sizeof(TbVarRef)); + if (self->userdata) { + memset(self->userdata, 0, sizeof(TbVarRef)); + /* nome no proprio campo (nada encaixado): o texto nao muda mais */ + ((TbVarRef*)self->userdata)->fixed = self->input_count > 0 && !self->inputs[0].source; + } } return (TbVarRef*)self->userdata; } @@ -134,8 +138,10 @@ static bool variables_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { TinyBlocks_TypeBlock* t; t = tb_type_block_create(rt, "Variables.Set", var_set, 2, NULL, 0, eval_var_set); if (!t || !tb_library_add(lib, &t->base)) return false; + tb_type_block_set_pure(t, TB_PURE_SET_VAR, NULL, 2); /* executor pode compilar */ t = tb_type_block_create(rt, "Variables.Change", var_set, 2, NULL, 0, eval_var_change); if (!t || !tb_library_add(lib, &t->base)) return false; + tb_type_block_set_pure(t, TB_PURE_CHANGE_VAR, NULL, 2); /* executor pode compilar */ t = tb_type_block_create(rt, "Variables.Get", var_in, 1, any_out, 1, eval_var_get); if (!t || !tb_library_add(lib, &t->base)) return false; tb_type_block_set_pure(t, TB_PURE_VAR, NULL, 1); /* executor pode compilar */ diff --git a/libraries/tinyblocks-vector/src/tb_vector.c b/libraries/tinyblocks-vector/src/tb_vector.c index d373d93..ec149c4 100644 --- a/libraries/tinyblocks-vector/src/tb_vector.c +++ b/libraries/tinyblocks-vector/src/tb_vector.c @@ -414,14 +414,6 @@ typedef struct { char name[64]; TinyBlocks_JsonValue* arr; } NamedList; static NamedList* s_named = NULL; /* cresce: quantas listas o programa quiser */ static int s_named_n = 0, s_named_cap = 0; -static const char* in_name(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, char* buf, size_t cap) { - TinyBlocks_Value v = tb_block_get_input(self, rt, i); - if (v.kind == TB_VALUE_TEXT && v.as.text) snprintf(buf, cap, "%s", v.as.text); - else if (v.kind == TB_VALUE_INTEGER) snprintf(buf, cap, "%lld", (long long)v.as.integer); - else buf[0] = 0; - return buf; -} - /* Lista com esse nome (criada vazia na primeira vez); NULL se o nome e vazio */ static NamedList* named_get(const char* name) { if (!name[0]) return NULL; @@ -439,6 +431,30 @@ static NamedList* named_get(const char* name) { return L; } +/* Lista da entrada i do bloco. O bloco guarda o indice da lista que achou + * (userdata) e so confere o nome: sem copiar o nome nem procurar entre + * todas as listas a cada acesso (item de lista e o que um laco mais faz). */ +static NamedList* named_of(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + const char* name; + char num[32]; + if (v.kind == TB_VALUE_TEXT && v.as.text) name = v.as.text; + else if (v.kind == TB_VALUE_INTEGER) { snprintf(num, sizeof(num), "%lld", (long long)v.as.integer); name = num; } + else return NULL; + if (!name[0] || strlen(name) >= sizeof(s_named[0].name)) return NULL; + int* cache = self->userdata; + if (!cache) { + cache = tb_alloc(rt, sizeof(int)); + if (cache) *cache = -1; + self->userdata = cache; + } + if (cache && *cache >= 0 && *cache < s_named_n && !strcmp(s_named[*cache].name, name)) + return &s_named[*cache]; + NamedList* L = named_get(name); + if (L && cache) *cache = (int)(L - s_named); + return L; +} + /* Troca o conteudo (toma a referencia de arr) */ static void named_set(NamedList* L, TinyBlocks_JsonValue* arr) { if (!L || !arr) { if (arr) tb_json_release(arr); return; } @@ -462,8 +478,7 @@ static long long in_pos(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, uint * a lista no lugar, em tempo constante (inserir/apagar: linear no que vem * depois). Ler um item de uma lista de 10 mil nao copia 10 mil itens. */ static void eval_var(TinyBlocks_Block* self, TinyBlocks* rt) { - char nm[64]; - NamedList* L = named_get(in_name(self, rt, 0, nm, sizeof(nm))); + NamedList* L = named_of(self, rt, 0); if (L) tb_json_retain(L->arr); out_list(self, L ? L->arr : tb_json_array()); } @@ -471,8 +486,7 @@ static void eval_var(TinyBlocks_Block* self, TinyBlocks* rt) { /* Array da lista (com referencia: avaliar outro campo pode criar listas e * mover s_named, mas o array continua o mesmo); NULL se o nome e vazio */ static TinyBlocks_JsonValue* named_arr(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { - char nm[64]; - NamedList* L = named_get(in_name(self, rt, i, nm, sizeof(nm))); + NamedList* L = named_of(self, rt, i); if (!L) return NULL; tb_json_retain(L->arr); return L->arr; @@ -530,9 +544,8 @@ static void eval_set_at(TinyBlocks_Block* self, TinyBlocks* rt) { /* "mude a lista [nome] para [lista]": guarda o resultado de outro bloco */ static void eval_assign(TinyBlocks_Block* self, TinyBlocks* rt) { - char nm[64]; TinyBlocks_JsonValue* src = in_list(self, rt, 1); /* antes: pode criar listas */ - NamedList* L = named_get(in_name(self, rt, 0, nm, sizeof(nm))); + NamedList* L = named_of(self, rt, 0); if (L && src) named_set(L, tb_json_clone(src)); if (src) tb_json_release(src); self->dirty = false; diff --git a/src/tb_vars.c b/src/tb_vars.c index af9eb97..e9af8b3 100644 --- a/src/tb_vars.c +++ b/src/tb_vars.c @@ -28,7 +28,11 @@ struct TbVarScope { }; static VarTable s_global; -static uint32_t s_gen = 1; /* muda quando uma variavel e criada/apagada ou um escopo morre (TbVarRef) */ +/* gen muda quando uma variavel e criada/apagada ou um escopo morre (TbVarRef); + scope espelha s_cur. Exposto (tb_vars_epoch) para codigo compilado conferir + sem chamar funcao. */ +static TbVarsEpoch s_epoch = { 1, NULL }; +#define s_gen (s_epoch.gen) static TbVarScope* s_cur = NULL; static TbVarScope* s_live = NULL; @@ -145,14 +149,16 @@ void tb_vars_scope_free(TbVarScope* s) { if (*pp == s) { *pp = s->next_live; break; } for (TbVarScope* o = s_live; o; o = o->next_live) /* filhos perdem o pai */ if (o->parent == s) o->parent = NULL; - if (s_cur == s) s_cur = NULL; + if (s_cur == s) { s_cur = NULL; s_epoch.scope = NULL; } s_gen++; table_clear(&s->t); free(s); } TbVarScope* tb_vars_scope_current(void) { return s_cur; } -void tb_vars_scope_set(TbVarScope* s) { s_cur = s; } +void tb_vars_scope_set(TbVarScope* s) { s_cur = s; s_epoch.scope = s; } + +const TbVarsEpoch* tb_vars_epoch(void) { return &s_epoch; } /* -- Valores --- */ diff --git a/tests/editor_harness.c b/tests/editor_harness.c index ca72c26..954212f 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -1411,7 +1411,9 @@ int main(void) { "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); + "say (join [g=] ((n) * (n)))\\n" + "set [m v] to (n)\\nchange [m v] by (0.5)\\nset [m v] to ((m) * (2))\\n" + "set [s v] to (t)\\nchange [k2 v] by (3)\\nsay (join (join [h=] (m)) (join (s) (k2)))\\n\",\"x\":40,\"y\":40}", &err, NULL); CHECK(!err, "contas: cria o script"); free(t); flag(); @@ -1423,6 +1425,8 @@ int main(void) { 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"); + CHECK(console_has("h=15abc3"), "comando compilado: mude para (variável / conta com ela mesma), mude por (0.5), " + "texto copiado, mude por cria a variável"); stop(); } diff --git a/tests/vm_bench.c b/tests/vm_bench.c index edee75a..e1938ee 100644 --- a/tests/vm_bench.c +++ b/tests/vm_bench.c @@ -85,7 +85,18 @@ int main(int argc, char** argv) { 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(); } + for (int k = 0; k < frames; k++) { + tb_vars_set("mudou", tb_value_integer(1)); + const char* cam = getenv("BENCH_CAM"); + if (cam) { + double c[4] = {0}; + sscanf(cam, "%lf,%lf,%lf,%lf", &c[0], &c[1], &c[2], &c[3]); + const char* nm[4] = { "cx", "cy", "cz", "pit" }; + for (int q = 0; q < 4; q++) tb_vars_set(nm[q], tb_value_real(c[q])); + tb_vars_set("yaw", tb_value_integer(270)); + } + frame(); + } return 0; } double t0 = now(); @@ -95,7 +106,14 @@ int main(int argc, char** argv) { 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)); + const char* cam = getenv("BENCH_CAM"); /* "cx,cy,cz,pit": camera fixa */ + if (cam) { + double c[4] = {0}; + sscanf(cam, "%lf,%lf,%lf,%lf", &c[0], &c[1], &c[2], &c[3]); + const char* nm[4] = { "cx", "cy", "cz", "pit" }; + for (int q = 0; q < 4; q++) tb_vars_set(nm[q], tb_value_real(c[q])); + } + tb_vars_set("yaw", tb_value_integer(k * (getenv("BENCH_STEP") ? atoi(getenv("BENCH_STEP")) : 3))); double a = now(); t_eval = t_draw = 0; int m = 0;