From 25bb30d12fdbab858b7764b0ad24dd8ec9160a56 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Mon, 26 Oct 2026 23:38:20 -0300 Subject: [PATCH] scratchblocks: Meus Blocos (define, parametros e chamadas) Importar: uma pre-passada acha os "define nome (a) rotulo " e cria um modelo User. para as chamadas casarem mesmo antes da definicao; o chamador e avisado (TbSbContext.define). No corpo, (x) com o nome de uma entrada vira Port.In. "fim" e "senao" valem como end e else. Exportar: o defina sai como "define " (TbSbContext.proto), o parametro como (x :: custom-arg) ou e as chamadas pelo rotulo do prototipo, com entradas ( ). No editor, a definicao importada registra o tipo User. com as saidas dos "devolva" do corpo. Agentes (MCP) e o forum agora criam e usam blocos proprios. Co-Authored-By: Claude Opus 5.5 --- libraries/tinyblocks-editor/src/tb_editor.c | 72 +++++++++- .../include/tb_scratchblocks.h | 13 +- .../src/tb_scratchblocks.c | 129 ++++++++++++++++-- tests/scratchblocks_test.c | 46 ++++++- 4 files changed, 248 insertions(+), 12 deletions(-) diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index b5a6bc0..1d4ce70 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -3233,6 +3233,7 @@ static int sb_slot_kind(const char* type, int slot, void* ud) { TinyBlocks_TypeBlock* t = tb_type_block_find(ed->rt, type); if (!t || slot < 0 || slot >= input_count(t)) return TB_SB_SLOT_TEXT; if (slot_is_bool(t, slot)) return TB_SB_SLOT_BOOL; + if (!strncmp(type, "User.", 5)) return TB_SB_SLOT_NUM; /* entrada de Meus Blocos: ( ) */ TinyBlocks_ValueKind k = t->input_descs[slot].expected_kind; return (k == TB_VALUE_INTEGER || k == TB_VALUE_REAL) ? TB_SB_SLOT_NUM : TB_SB_SLOT_TEXT; } @@ -3253,11 +3254,59 @@ static const char* sb_category(const char* type, void* ud) { return "extension"; } +/* == Meus Blocos no scratchblocks === + * Rotulo de chamada ("dobro %1") e prototipo ("dobro (n)") de cada bloco do + * usuario, e os que a importacao definiu (para registrar os tipos depois). */ +static char s_sb_call[MAX_USER_BLOCKS][256]; +static bool s_sb_touched[MAX_USER_BLOCKS]; + +static void user_label(const UserBlockDef* def, char* out, size_t cap, bool proto) { + size_t n = (size_t)snprintf(out, cap, "%s", def->name); + int k = 0; + for (int i = 0; i < def->part_n && n < cap; i++) { + const UserParam* p = &def->parts[i]; + if (p->kind == PARAM_LABEL) n += (size_t)snprintf(out + n, cap - n, " %s", p->name); + else if (!proto) n += (size_t)snprintf(out + n, cap - n, " %%%d", ++k); + else n += (size_t)snprintf(out + n, cap - n, p->kind == PARAM_BOOL ? " <%s>" : " (%s)", + p->name[0] ? p->name : "entrada"); + } +} + +static const char* sb_proto(const char* name, void* ud) { + static char buf[256]; + UserBlockDef* def = user_def_find((Ed*)ud, name); + if (!def) return NULL; + user_label(def, buf, sizeof(buf), true); + return buf; +} + +/* "define ..." no texto: cria ou atualiza a definicao (o tipo vem depois) */ +static void sb_define(const char* name, const TbBpParam* parts, int n, bool reporter, void* ud) { + (void)reporter; /* as saidas vem dos "devolva" do corpo */ + Ed* ed = (Ed*)ud; + UserBlockDef* def = user_def_find(ed, name); + if (!def) { + if (ed->user_block_n >= MAX_USER_BLOCKS) return; + def = &ed->user_blocks[ed->user_block_n++]; + memset(def, 0, sizeof(*def)); + snprintf(def->name, sizeof(def->name), "%s", name); + def->tab_idx = -1; + } + def->part_n = 0; + for (int i = 0; i < n && def->part_n < MAX_UBLK_PARTS; i++) { + UserParam* p = &def->parts[def->part_n++]; + p->kind = (ParamKind)parts[i].kind; + snprintf(p->name, sizeof(p->name), "%s", parts[i].name); + } + comp_build_input_names(def); + s_sb_touched[def - ed->user_blocks] = true; +} + /* Contexto: rotulos em portugues do editor + callbacks */ static TbSbContext sb_context(Ed* ed, TbSbLabel** labels_out) { size_t n = sizeof(s_specs) / sizeof(s_specs[0]); uint32_t nt = tb_rt_type_count(ed->rt); - TbSbLabel* L = calloc(n + nt, sizeof(TbSbLabel)); + TbSbLabel* L = calloc(n + nt + MAX_USER_BLOCKS, sizeof(TbSbLabel)); int k = 0; for (size_t i = 0; L && i < n; i++) { L[k].type = s_specs[i].type; @@ -3271,8 +3320,16 @@ static TbSbContext sb_context(Ed* ed, TbSbLabel** labels_out) { L[k].label = t->label; k++; } + for (int u = 0; L && u < ed->user_block_n; u++) { /* chamadas de Meus Blocos */ + UserBlockDef* def = &ed->user_blocks[u]; + if (!def->reg_type) continue; + user_label(def, s_sb_call[u], sizeof(s_sb_call[u]), false); + L[k].type = def->reg_type->type_name; + L[k].label = s_sb_call[u]; + k++; + } *labels_out = L; - TbSbContext cx = { L, L ? k : 0, sb_shape, sb_slot_kind, sb_category, ed }; + TbSbContext cx = { L, L ? k : 0, sb_shape, sb_slot_kind, sb_category, ed, sb_define, sb_proto }; return cx; } @@ -3306,6 +3363,7 @@ int ed_scratchblocks_import(Ed* ed, Tab* T, const char* text, float x, float y, if (!B) return -1; TbSbLabel* labels = NULL; TbSbContext cx = sb_context(ed, &labels); + memset(s_sb_touched, 0, sizeof(s_sb_touched)); int n = tb_scratchblocks_import(text, B, &cx, warn, warn_cap); free(labels); if (n <= 0) { bp_tab_dispose(B); return -1; } @@ -3351,6 +3409,16 @@ int ed_scratchblocks_import(Ed* ed, Tab* T, const char* text, float x, float y, } free(map); bp_tab_dispose(B); + /* "define" do texto: registra (ou refaz) o tipo User. com as + entradas do prototipo e as saidas dos "devolva" do corpo */ + for (int u = 0; u < ed->user_block_n; u++) { + if (!s_sb_touched[u]) continue; + UserBlockDef* def = &ed->user_blocks[u]; + int t, hat = define_find(ed, def->name, &t); + def->output_count = 0; + if (hat >= 0) define_outputs(&ed->tabs[t], ed->tabs[t].ws[hat].next, def->output_names, &def->output_count); + comp_make_type(ed, def); + } layout_tab(T); /* empilha uma embaixo da outra */ for (int k = 1; k < made && k < max && heads; k++) { float x0, y0, x1, y1; diff --git a/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h b/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h index 95d3b9c..118d1b1 100644 --- a/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h +++ b/libraries/tinyblocks-scratchblocks/include/tb_scratchblocks.h @@ -14,7 +14,8 @@ * como no Scratch). Os demais usam os rotulos passados pelo chamador (ex.: * os do editor, em portugues) com "::categoria". A importacao aceita as * duas formas. Nao conhece o editor: forma do bloco, tipo de cada campo e - * categoria chegam por callbacks. + * categoria chegam por callbacks. Meus Blocos: "define nome (entrada) " + * e as chamadas "nome (1) <...>" (ver TbSbContext.define). */ #ifndef TINYBLOCKS_SCRATCHBLOCKS_H #define TINYBLOCKS_SCRATCHBLOCKS_H @@ -58,6 +59,16 @@ typedef struct { sensing, operators, variables, list, pen, custom, extension...) */ const char* (*category)(const char* type, void* ud); void* ud; + /* Meus Blocos (podem ser NULL): + define: a importacao achou "define ": o nome e as partes + na ordem (rotulos e entradas); reporter = o corpo tem "devolva". O + chamador cria o bloco ("User."); as chamadas no mesmo texto ja + casam pelo prototipo. Dentro do corpo, (x) com o nome de uma entrada + vira "Port.In" (o parametro), nao variavel. + proto: o prototipo de um bloco definido, como no texto ("dobro (n)"), + para exportar o "define"; NULL = so o nome. */ + void (*define)(const char* name, const TbBpParam* parts, int n, bool reporter, void* ud); + const char* (*proto)(const char* name, void* ud); } TbSbContext; /* Texto da aba (todas as pilhas, de cima para baixo). malloc; NULL em erro. */ diff --git a/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c b/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c index 773a62c..3cca238 100644 --- a/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c +++ b/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c @@ -308,14 +308,69 @@ typedef struct { const TbSbContext* cx; } Models; +/* "define nome (a) rotulo ": um bloco do usuario achado no texto */ +#define PROTO_MAX 64 +typedef struct { + char type[64]; /* "User." */ + char name[48]; + char text[512]; /* modelo: "nome %1 rotulo %2" */ + bool reporter; + TbBpParam parts[TB_BP_MAX_UPARTS]; + int part_n; +} Proto; + +static bool is_define(const char* line) { + return !strncasecmp(line, "define ", 7) || !strncasecmp(line, "defina ", 7); +} + +/* Le o prototipo depois de "define ": nome = as palavras do comeco; depois, + ( ) e [ ] sao entradas, < > booleanas e palavras sao rotulos */ +static bool proto_parse(const char* rest, Proto* p) { + memset(p, 0, sizeof(*p)); + char buf[512]; + snprintf(buf, sizeof(buf), "%.500s", rest); + strip_category(buf); + Tok t[TOK_MAX]; + int n = tokenize(buf, t, TOK_MAX); + if (n <= 0 || t[0].kind != T_WORD) return false; + int i = 0; + size_t tl = 0; + for (; i < n && t[i].kind == T_WORD; i++) { + size_t w = strlen(p->name); + snprintf(p->name + w, sizeof(p->name) - w, "%s%s", w ? " " : "", t[i].text); + } + snprintf(p->type, sizeof(p->type), "User.%s", p->name); + tl = (size_t)snprintf(p->text, sizeof(p->text), "%s", p->name); + int inputs = 0; + for (; i < n && p->part_n < TB_BP_MAX_UPARTS; i++) { + TbBpParam* q = &p->parts[p->part_n++]; + snprintf(q->name, sizeof(q->name), "%.31s", t[i].text); + if (t[i].kind == T_WORD) { + q->kind = TB_BP_PARAM_LABEL; + tl += (size_t)snprintf(p->text + tl, tl < sizeof(p->text) ? sizeof(p->text) - tl : 0, " %s", t[i].text); + } else { + q->kind = t[i].kind == T_ANGLE ? TB_BP_PARAM_BOOL : TB_BP_PARAM_NUM; + tl += (size_t)snprintf(p->text + tl, tl < sizeof(p->text) ? sizeof(p->text) - tl : 0, " %%%d", ++inputs); + } + } + return true; +} + +/* O nome e uma entrada (numero/texto ou booleana) do prototipo? */ +static bool proto_has_param(const Proto* p, const char* name) { + for (int i = 0; p && i < p->part_n; i++) + if (p->parts[i].kind != TB_BP_PARAM_LABEL && !strcmp(p->parts[i].name, name)) return true; + return false; +} + static int cx_shape(const TbSbContext* cx, const char* type) { return cx && cx->shape ? cx->shape(type, cx->ud) : -1; } -static Models models_load(const TbSbContext* cx) { +static Models models_load_with(const TbSbContext* cx, const Proto* protos, int np) { Models M = { NULL, 0, cx }; int extra = cx && cx->labels ? cx->label_n : 0; - M.m = calloc((size_t)(BUILTIN_N + extra), sizeof(Model)); + M.m = calloc((size_t)(BUILTIN_N + extra + np), sizeof(Model)); if (!M.m) return M; for (int i = 0; i < BUILTIN_N; i++) { Model* m = &M.m[M.n]; @@ -334,9 +389,13 @@ static Models models_load(const TbSbContext* cx) { if (m->n == 1 && m->slot[0] >= 0) continue; M.n++; } + for (int i = 0; i < np; i++) /* chamadas de Meus Blocos */ + if (model_build(&M.m[M.n], protos[i].type, protos[i].text, protos[i].reporter ? 'r' : 's', false)) M.n++; return M; } +static Models models_load(const TbSbContext* cx) { return models_load_with(cx, NULL, 0); } + static bool word_eq(const char* a, const char* b) { return strcasecmp(a, b) == 0; } @@ -424,6 +483,10 @@ static void render_slot(const Models* M, const TbBpTab* tab, int bi, int s, int sb_str(out, kind == T_ROUND ? "(" : "["); sb_esc(out, v); sb_str(out, kind == T_ROUND ? ")" : "]"); return; } + if (c >= 0 && kind == T_ANGLE && !strcmp(tab->blocks[c].type, "Port.In")) { /* */ + sb_str(out, "<"); render_block(M, tab, c, out, false); sb_str(out, ">"); + return; + } if (c >= 0) { render_block(M, tab, c, out, true); return; } const char* v = s < TB_BP_MAX_INPUTS ? b->in_text[s] : ""; if (kind == T_ANGLE) { sb_str(out, "<>"); return; } @@ -472,6 +535,13 @@ static void render_block(const Models* M, const TbBpTab* tab, int bi, Sb* out, b if (outer && boo) sb_str(out, "<"); if (strcmp(b->type, "Variables.Get") == 0) { /* (x): valor da variavel */ sb_esc(out, b->in_text[0]); + } else if (strcmp(b->type, "Port.Define") == 0) { /* define nome (a) */ + const char* pr = M->cx && M->cx->proto ? M->cx->proto(b->in_text[0], M->cx->ud) : NULL; + sb_str(out, "define "); + if (pr) sb_str(out, pr); else sb_esc(out, b->in_text[0]); + } else if (strcmp(b->type, "Port.In") == 0) { /* (n :: custom-arg) */ + sb_esc(out, b->in_text[0]); + sb_str(out, " :: custom-arg"); } else if (is_literal(b->type)) { sb_esc(out, strcmp(b->type, "Literal.Text") == 0 && b->lit[0] ? b->lit : b->in_text[0]); } else { @@ -557,6 +627,7 @@ typedef struct { char* warn; size_t warn_cap; int line; + const Proto* in_define; /* corpo de um "define": (x) pode ser parametro */ } Imp; static void imp_warn(Imp* I, const char* what, const char* text) { @@ -667,6 +738,11 @@ static int parse_inner(Imp* I, const char* text, char cls) { } bool words = n > 0; for (int i = 0; i < n; i++) if (t[i].kind != T_WORD) words = false; + if (words && cls != 's' && proto_has_param(I->in_define, buf)) { /* parametro do define */ + int bi = new_block(I, "Port.In"); + if (bi >= 0) snprintf(I->tab->blocks[bi].in_text[0], 64, "%.63s", buf); + return bi; + } if (words && cls == 'r') { /* (x): variavel */ int bi = new_block(I, "Variables.Get"); if (bi >= 0) snprintf(I->tab->blocks[bi].in_text[0], 64, "%.63s", buf); @@ -698,9 +774,31 @@ int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* c char* warn, size_t warn_cap) { if (!text || !out) return -1; if (warn && warn_cap) warn[0] = 0; - Models M = models_load(cx); - if (!M.m) return -1; - Imp I = { &M, out, warn, warn_cap, 0 }; + /* pre-passada: os "define" (as chamadas podem vir antes da definicao) */ + Proto* protos = calloc(PROTO_MAX, sizeof(Proto)); + int np = 0; + for (const char* q = text; protos && *q; ) { + const char* e = strchr(q, '\n'); + size_t len = e ? (size_t)(e - q) : strlen(q); + char line[1024]; + if (len >= sizeof(line)) len = sizeof(line) - 1; + memcpy(line, q, len); line[len] = 0; + q = e ? e + 1 : q + len; + clean_line(line); + if (is_define(line)) { + if (np < PROTO_MAX && proto_parse(line + 7, &protos[np])) np++; + } else if (!line[0]) { + /* fim do script: nada */ + } else if (np > 0 && (!strncasecmp(line, "devolva", 7) || !strncasecmp(line, "report", 6))) { + protos[np - 1].reporter = true; + } + } + for (int i = 0; i < np; i++) + if (cx && cx->define) cx->define(protos[i].name, protos[i].parts, protos[i].part_n, protos[i].reporter, cx->ud); + Models M = models_load_with(cx, protos, np); + if (!M.m) { free(protos); return -1; } + Imp I = { &M, out, warn, warn_cap, 0, NULL }; + int define_k = 0; Level lv[LEVEL_MAX]; int depth = 0, stacks = 0; lv[0].cblock = -1; lv[0].sub = 0; lv[0].last = -1; @@ -719,11 +817,24 @@ int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* c clean_line(line); if (!strncasecmp(line, "[scratchblocks]", 15) || !strncasecmp(line, "[/scratchblocks]", 16)) continue; if (!line[0]) { /* linha em branco: fim do script */ - if (depth == 0) lv[0].last = -1; + if (depth == 0) { lv[0].last = -1; I.in_define = NULL; } continue; } - if (!strcasecmp(line, "end")) { if (depth > 0) depth--; continue; } - if (!strcasecmp(line, "else")) { + if (is_define(line)) { /* chapeu "defina" */ + const Proto* pr = define_k < np ? &protos[define_k++] : NULL; + int bi = pr ? new_block(&I, "Port.Define") : -1; + if (bi < 0) { imp_warn(&I, "define inválido", line); continue; } + snprintf(out->blocks[bi].in_text[0], sizeof(out->blocks[bi].in_text[0]), "%.63s", pr->name); + depth = 0; + out->blocks[bi].x = 40; out->blocks[bi].y = y; y += 120; + tb_blueprint_top_add(out, bi); + stacks++; + lv[0].last = bi; + I.in_define = pr; + continue; + } + if (!strcasecmp(line, "end") || !strcasecmp(line, "fim")) { if (depth > 0) depth--; continue; } + if (!strcasecmp(line, "else") || !strcasecmp(line, "senão") || !strcasecmp(line, "senao")) { if (depth > 0) { TbBpBlock* c = &out->blocks[lv[depth].cblock]; if (!strcmp(c->type, "Control.If")) snprintf(c->type, sizeof(c->type), "Control.IfElse"); @@ -764,6 +875,7 @@ int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* c bool after_cap = prev >= 0 && block_shape(&M, out->blocks[prev].type) == TB_SB_CAP; if (outer || sh == TB_SB_HAT || after_cap || (depth == 0 && lv[0].last < 0)) { /* comeca uma pilha nova */ + if (sh == TB_SB_HAT) I.in_define = NULL; depth = 0; out->blocks[bi].x = 40; out->blocks[bi].y = y; @@ -783,5 +895,6 @@ int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* c } } free(M.m); + free(protos); return stacks; } diff --git a/tests/scratchblocks_test.c b/tests/scratchblocks_test.c index c1cd8a6..5a93daa 100644 --- a/tests/scratchblocks_test.c +++ b/tests/scratchblocks_test.c @@ -34,7 +34,7 @@ static const char* category(const char* type, void* ud) { return !strncmp(type, "Stage.", 6) ? "pen" : "extension"; } -static const TbSbContext CX = { s_labels, (int)(sizeof(s_labels) / sizeof(s_labels[0])), shape, slot_kind, category, NULL }; +static const TbSbContext CX = { s_labels, (int)(sizeof(s_labels) / sizeof(s_labels[0])), shape, slot_kind, category, NULL, NULL, NULL }; static TbBpTab* fresh(void) { return calloc(1, sizeof(TbBpTab)); } @@ -73,6 +73,15 @@ static const char* EXPECTED = "add [maçã] to [frutas v]\n" "say (item (1) of [frutas v])\n"; +static int s_def_n, s_def_parts; +static bool s_def_rep; +static char s_def_name[48]; +static void on_define(const char* name, const TbBpParam* parts, int n, bool reporter, void* ud) { + (void)parts; (void)ud; + s_def_n++; s_def_parts = n; s_def_rep = reporter; + snprintf(s_def_name, sizeof(s_def_name), "%s", name); +} + static int child(const TbBpTab* t, int bi, int s) { return bi >= 0 ? t->blocks[bi].args[s] : -1; } static const char* ty(const TbBpTab* t, int bi) { return bi >= 0 ? t->blocks[bi].type : "(nada)"; } @@ -198,6 +207,41 @@ int main(void) { } drop(t); + /* -- Meus Blocos: define, parametros e chamadas -------------------------- */ + { + TbSbContext cx = CX; + cx.define = on_define; + t = fresh(); + warn[0] = 0; + int n = tb_scratchblocks_import( + "when flag clicked\n" + "dobro (21) e <(1) = (1)> :: custom\n" + "\n" + "define dobro (n) e \n" + "if then\n" + " say ((n) * (2))\n" + "fim\n", t, &cx, warn, sizeof(warn)); + if (warn[0]) printf(" aviso: %s\n", warn); + CHECK(n == 2 && !warn[0], "define + chamada: 2 pilhas, sem aviso (fim em português)"); + CHECK(s_def_n == 1 && !strcmp(s_def_name, "dobro") && s_def_parts == 3 && !s_def_rep, + "define avisa o chamador: nome e 3 partes (entrada, rótulo, booleana)"); + int call = t->top_n ? t->blocks[t->top[0]].next : -1; + CHECK(!strcmp(ty(t, call), "User.dobro") && !strcmp(t->blocks[call].in_text[0], "21"), + "a chamada antes do define já vira User.dobro (21)"); + int hat = t->top_n > 1 ? t->top[1] : -1; + int iff = hat >= 0 ? t->blocks[hat].next : -1; + int ret = iff >= 0 ? t->blocks[iff].sub[0] : -1; + int mul = child(t, ret, 0); + CHECK(!strcmp(ty(t, hat), "Port.Define") && !strcmp(t->blocks[hat].in_text[0], "dobro") && + !strcmp(ty(t, child(t, iff, 0)), "Port.In") && !strcmp(ty(t, child(t, mul, 0)), "Port.In"), + "no corpo, (n) e viram parâmetros (Port.In), não variáveis"); + drop(t); + t = fresh(); + tb_scratchblocks_import("say (n)\n", t, &cx, warn, sizeof(warn)); + CHECK(!strcmp(ty(t, child(t, t->top_n ? t->top[0] : -1, 0)), "Variables.Get"), "fora do define, (n) é variável"); + drop(t); + } + if (fails) printf("\n%d FALHA(S)\n", fails); else printf("\nTUDO OK\n"); return fails != 0;