scratchblocks: Meus Blocos (define, parametros e chamadas)

Importar: uma pre-passada acha os "define nome (a) rotulo <b>" e cria um
modelo User.<nome> 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 <prototipo>" (TbSbContext.proto),
o parametro como (x :: custom-arg) ou <x :: custom-arg> e as chamadas
pelo rotulo do prototipo, com entradas ( ).

No editor, a definicao importada registra o tipo User.<nome> 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 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-26 23:38:20 -03:00
1 parent 756540eb76
commit 25bb30d12f
4 files changed
+248 -12

No files matched your search

@@ -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) <bool>"
* 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 <prototipo>": o nome e as partes
na ordem (rotulos e entradas); reporter = o corpo tem "devolva". O
chamador cria o bloco ("User.<nome>"); 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. */
@@ -308,14 +308,69 @@ typedef struct {
const TbSbContext* cx;
} Models;
/* "define nome (a) rotulo <b>": um bloco do usuario achado no texto */
#define PROTO_MAX 64
typedef struct {
char type[64]; /* "User.<nome>" */
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")) { /* <ok :: custom-arg> */
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) <b> */
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;
}