/* * TinyBlocks - tb_scratchblocks.c * Notacao de texto do forum do Scratch ("scratchblocks") <-> aba de blocos * (TbBpTab da tinyblocks-blueprint). Ver tb_scratchblocks.h. * * Um modelo descreve um tipo de bloco no texto de dentro dele: * "set [%1 v] to (%2)" -> %N e o campo N (1-based), com o tipo de * parenteses que sai na exportacao * "item (%2) of [%L1 v]" -> %LN: o campo N recebe uma lista com nome * (repórter List.Var), escrita como menu * "[abs v] of (%1)" -> campo fixo: so casa com esse texto * Exportar troca os %N pelos valores; importar reduz a linha a palavras e * campos e procura o modelo que casa posicao a posicao. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include "tb_scratchblocks.h" /* -- Modelos internos (ingles do Scratch 3) ------------------------------- */ /* forma: h chapeu, s comando, c C, C se/senao, e sempre, r repórter, b booleano */ typedef struct { const char* type; const char* text; char shape; bool import_only; } Tpl; static const Tpl s_builtin[] = { {"Events.WhenRun", "when flag clicked", 'h', false}, {"Events.WhenRun", "when green flag clicked", 'h', true}, {"Control.Repeat", "repeat (%1)", 'c', false}, {"Control.RepeatUntil", "repeat until <%1>", 'c', false}, {"Control.Forever", "forever", 'e', false}, {"Control.If", "if <%1> then", 'c', false}, {"Control.IfElse", "if <%1> then", 'C', false}, {"Variables.Set", "set [%1 v] to (%2)", 's', false}, {"Variables.Change", "change [%1 v] by (%2)", 's', false}, {"IO.Print", "say [%1]", 's', false}, {"Stage.Clear", "erase all", 's', false}, {"Stage.PenSize", "set pen size to (%1)", 's', false}, {"Input.ResetTimer", "reset timer", 's', false}, {"List.Push", "add [%1] to [%2 v]", 's', false}, {"List.DeleteAt", "delete (%1) of [%2 v]", 's', false}, {"List.Clear", "delete all of [%1 v]", 's', false}, {"List.InsertAt", "insert [%1] at (%2) of [%3 v]", 's', false}, {"List.SetAt", "replace item (%1) of [%2 v] with [%3]", 's', false}, {"Operators.Lt", "(%1) < (%2)", 'b', false}, {"Operators.Eq", "(%1) = (%2)", 'b', false}, {"Operators.Gt", "(%1) > (%2)", 'b', false}, {"Operators.And", "<%1> and <%2>", 'b', false}, {"Operators.Or", "<%1> or <%2>", 'b', false}, {"Operators.Not", "not <%1>", 'b', false}, {"List.Contains", "[%L1 v] contains [%2]?", 'b', false}, {"String.Contains", "[%1] contains [%2]?", 'b', false}, {"Input.MouseDown", "mouse down?", 'b', false}, {"Input.KeyPressed", "key [%1 v] pressed?", 'b', false}, {"Operators.Random", "pick random (%1) to (%2)", 'r', false}, {"Math.Add", "(%1) + (%2)", 'r', false}, {"Math.Sub", "(%1) - (%2)", 'r', false}, {"Math.Mul", "(%1) * (%2)", 'r', false}, {"Number.Div", "(%1) / (%2)", 'r', false}, {"Math.Div", "(%1) / (%2)", 'r', false}, {"Math.Mod", "(%1) mod (%2)", 'r', false}, {"Number.Round", "round (%1)", 'r', false}, {"Math.Abs", "[abs v] of (%1)", 'r', false}, {"Number.Floor", "[floor v] of (%1)", 'r', false}, {"Number.Ceil", "[ceiling v] of (%1)", 'r', false}, {"Number.Sqrt", "[sqrt v] of (%1)", 'r', false}, {"Number.Sin", "[sin v] of (%1)", 'r', false}, {"Number.Cos", "[cos v] of (%1)", 'r', false}, {"Number.Tan", "[tan v] of (%1)", 'r', false}, {"Number.Asin", "[asin v] of (%1)", 'r', false}, {"Number.Acos", "[acos v] of (%1)", 'r', false}, {"Number.Atan", "[atan v] of (%1)", 'r', false}, {"Number.Ln", "[ln v] of (%1)", 'r', false}, {"Number.Log10", "[log v] of (%1)", 'r', false}, {"Number.Exp", "[e ^ v] of (%1)", 'r', false}, {"Text.Concat", "join [%1] [%2]", 'r', false}, {"List.Length", "length of [%L1 v]", 'r', false}, {"Text.Length", "length of [%1]", 'r', false}, {"String.Letter", "letter (%2) of [%1]", 'r', false}, {"List.Item", "item (%2) of [%L1 v]", 'r', false}, {"List.IndexOf", "item # of [%2] in [%L1 v]", 'r', false}, {"List.Var", "[%1 v] :: list", 'r', false}, {"Input.MouseX", "mouse x", 'r', false}, {"Input.MouseY", "mouse y", 'r', false}, {"Input.Timer", "timer", 'r', false}, }; #define BUILTIN_N ((int)(sizeof(s_builtin) / sizeof(s_builtin[0]))) /* -- Texto dinamico -------------------------------------------------------- */ typedef struct { char* p; size_t n, cap; } Sb; static void sb_add(Sb* b, const char* s, size_t n) { if (!b->p && b->cap == (size_t)-1) return; if (b->n + n + 1 > b->cap) { size_t nc = b->cap ? b->cap * 2 : 256; while (nc < b->n + n + 1) nc *= 2; char* np = realloc(b->p, nc); if (!np) { free(b->p); b->p = NULL; b->cap = (size_t)-1; return; } b->p = np; b->cap = nc; } memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; } static void sb_str(Sb* b, const char* s) { sb_add(b, s, strlen(s)); } /* texto de campo: escapa os caracteres da notacao */ static void sb_esc(Sb* b, const char* s) { for (; *s; s++) { if (strchr("[]()<>\\", *s)) sb_add(b, "\\", 1); sb_add(b, s, 1); } } /* -- Tokens ---------------------------------------------------------------- */ enum { T_WORD, T_ROUND, T_SQUARE, T_ANGLE }; /* palavra, ( ), [ ], < > */ #define TOK_MAX 40 #define TOK_TEXT 256 typedef struct { int kind; bool dropdown; char text[TOK_TEXT]; } Tok; /* fim do grupo que abre em s[i] (indice do fechamento) ou -1 */ static int group_end(const char* s, int i) { char open = s[i]; if (open == '[') { for (int k = i + 1; s[k]; k++) { if (s[k] == '\\' && s[k + 1]) { k++; continue; } if (s[k] == ']') return k; } return -1; } int depth = 0; for (int k = i; s[k]; k++) { char c = s[k]; if (c == '\\' && s[k + 1]) { k++; continue; } if (c == '[') { int e = group_end(s, k); if (e < 0) return -1; k = e; continue; } if (open == '(') { if (c == '(') depth++; else if (c == ')') { if (--depth == 0) return k; } } else { /* '<' booleano */ /* "<" e ">" com espaco dos dois lados sao os operadores menor/maior */ bool spaced = k > 0 && s[k - 1] == ' ' && s[k + 1] == ' '; if (c == '(') { int e = group_end(s, k); if (e < 0) return -1; k = e; continue; } if (c == '<' && !spaced && s[k + 1] != ' ') depth++; else if (c == '>' && !spaced) { if (--depth == 0) return k; } } } return -1; } static void copy_inner(char* out, const char* s, int a, int b, bool unescape, bool trim) { int n = 0; for (int k = a; k < b && n < TOK_TEXT - 1; k++) { if (unescape && s[k] == '\\' && k + 1 < b) k++; out[n++] = s[k]; } out[n] = 0; if (!trim) return; /* tira espacos das pontas */ char* p = out; while (*p == ' ') p++; if (p != out) memmove(out, p, strlen(p) + 1); n = (int)strlen(out); while (n > 0 && out[n - 1] == ' ') out[--n] = 0; } /* Divide o texto de um bloco em palavras e campos; -1 em erro de sintaxe */ static int tokenize(const char* s, Tok* t, int max) { int n = 0, i = 0; while (s[i] && n < max) { if (s[i] == ' ' || s[i] == '\t') { i++; continue; } char c = s[i]; bool is_group = c == '(' || c == '[' || (c == '<' && s[i + 1] && s[i + 1] != ' '); if (is_group) { int e = group_end(s, i); if (e < 0) return -1; Tok* k = &t[n++]; k->kind = c == '(' ? T_ROUND : c == '[' ? T_SQUARE : T_ANGLE; copy_inner(k->text, s, i + 1, e, c == '[', c != '['); k->dropdown = false; size_t L = strlen(k->text); if (c == '[' && L >= 2 && k->text[L - 1] == 'v' && k->text[L - 2] == ' ') { k->dropdown = true; /* menu: nome aparado */ k->text[L - 2] = 0; copy_inner(k->text, k->text, 0, (int)strlen(k->text), false, true); } else if (c == '[' && L == 1 && k->text[0] == 'v') { k->dropdown = true; k->text[0] = 0; } i = e + 1; continue; } int a = i; while (s[i] && s[i] != ' ' && s[i] != '\t' && s[i] != '(' && s[i] != '[' && !(s[i] == '<' && i > a)) i++; Tok* k = &t[n++]; k->kind = T_WORD; k->dropdown = false; int len = i - a < TOK_TEXT - 1 ? i - a : TOK_TEXT - 1; memcpy(k->text, s + a, (size_t)len); k->text[len] = 0; } return n; } /* Indice logo depois do grupo ( ) [ ] < > que abre em s[k], ou k+1 se nao for grupo */ static int skip_group(const char* s, int k) { char c = s[k]; if (c == '(' || c == '[' || (c == '<' && s[k + 1] && s[k + 1] != ' ')) { int e = group_end(s, k); return e < 0 ? (int)strlen(s) : e + 1; } return k + 1; } /* Tira " :: categoria" (fora dos campos) */ static void strip_category(char* s) { for (int k = 0; s[k]; ) { if (s[k] == '\\' && s[k + 1]) { k += 2; continue; } if (s[k] == '(' || s[k] == '[' || s[k] == '<') { k = skip_group(s, k); continue; } if (s[k] == ':' && s[k + 1] == ':') { s[k] = 0; int n = (int)strlen(s); while (n > 0 && s[n - 1] == ' ') s[--n] = 0; return; } k++; } } /* -- Modelos (internos + rotulos do chamador) ------------------------------ */ typedef struct { const char* type; char shape; bool builtin, import_only; int n; Tok tok[TOK_MAX]; int slot[TOK_MAX]; /* campo (0-based) do token; -1 = fixo/palavra */ bool listslot[TOK_MAX]; /* %LN */ char cat[24]; /* "list" de "... :: list" (modelos internos) */ } Model; static int shape_char(int sh) { switch (sh) { case TB_SB_HAT: return 'h'; case TB_SB_C1: return 'c'; case TB_SB_C2: return 'C'; case TB_SB_CAP: return 'e'; case TB_SB_REPORTER: return 'r'; case TB_SB_BOOLEAN: return 'b'; default: return 's'; } } /* "%N" ou "%LN" -> campo (0-based); -1 se nao for */ static int slot_ref(const char* s, bool* list) { *list = false; if (s[0] != '%') return -1; const char* p = s + 1; if (*p == 'L') { *list = true; p++; } if (!isdigit((unsigned char)*p)) return -1; int v = atoi(p); while (isdigit((unsigned char)*p)) p++; return *p ? -1 : v - 1; } static bool model_build(Model* m, const char* type, const char* text, char shape) { memset(m, 0, sizeof(*m)); m->type = type; m->shape = shape; char buf[512]; snprintf(buf, sizeof(buf), "%s", text); const char* cc = strstr(text, "::"); if (cc) { cc += 2; while (*cc == ' ') cc++; snprintf(m->cat, sizeof(m->cat), "%s", cc); } strip_category(buf); m->n = tokenize(buf, m->tok, TOK_MAX); if (m->n <= 0) return false; for (int i = 0; i < m->n; i++) { bool list; m->slot[i] = slot_ref(m->tok[i].text, &list); m->listslot[i] = list; } return true; } typedef struct { Model* m; int n; const TbSbContext* cx; } Models; 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) { Models M = { NULL, 0, cx }; int extra = cx && cx->labels ? cx->label_n : 0; M.m = calloc((size_t)(BUILTIN_N + extra), sizeof(Model)); if (!M.m) return M; for (int i = 0; i < BUILTIN_N; i++) { Model* m = &M.m[M.n]; if (!model_build(m, s_builtin[i].type, s_builtin[i].text, s_builtin[i].shape)) continue; m->builtin = true; m->import_only = s_builtin[i].import_only; M.n++; } for (int i = 0; i < extra; i++) { const TbSbLabel* L = &cx->labels[i]; if (!L->type || !L->label) continue; int sh = cx_shape(cx, L->type); Model* m = &M.m[M.n]; if (!model_build(m, L->type, L->label, (char)shape_char(sh < 0 ? TB_SB_STACK : sh))) continue; /* "%1" sozinho (ex.: valor de variavel) casaria com qualquer coisa */ if (m->n == 1 && m->slot[0] >= 0) continue; M.n++; } return M; } static bool word_eq(const char* a, const char* b) { return strcasecmp(a, b) == 0; } /* O modelo casa com os tokens? */ static bool model_match(const Model* m, const Tok* t, int n) { if (m->n != n) return false; for (int i = 0; i < n; i++) { const Tok* mt = &m->tok[i]; if (m->slot[i] >= 0) { if (t[i].kind == T_WORD) return false; if (m->listslot[i] && !(t[i].kind == T_SQUARE && t[i].dropdown)) return false; continue; } if (mt->kind != t[i].kind) { /* campo fixo "[abs v]" aceita tambem "(abs)" */ if (mt->kind == T_WORD || t[i].kind == T_WORD) return false; } if (!word_eq(mt->text, t[i].text)) return false; } return true; } static bool shape_is_stmt(char s) { return s == 's' || s == 'h' || s == 'c' || s == 'C' || s == 'e'; } /* -- Exportar -------------------------------------------------------------- */ static bool is_literal(const char* type) { return strncmp(type, "Literal.", 8) == 0; } static int block_shape(const Models* M, const char* type) { int sh = cx_shape(M->cx, type); if (sh >= 0) return sh; if (!strcmp(type, "Variables.Get") || is_literal(type)) return TB_SB_REPORTER; for (int i = 0; i < M->n; i++) { if (strcmp(M->m[i].type, type) != 0) continue; switch (M->m[i].shape) { case 'h': return TB_SB_HAT; case 'c': return TB_SB_C1; case 'C': return TB_SB_C2; case 'e': return TB_SB_CAP; case 'r': return TB_SB_REPORTER; case 'b': return TB_SB_BOOLEAN; default: return TB_SB_STACK; } } return TB_SB_STACK; } static bool slot_used(const TbBpTab* tab, int bi, int s) { const TbBpBlock* b = &tab->blocks[bi]; return b->args[s] >= 0 || b->in_text[s][0]; } /* O modelo serve para exportar este bloco? (cobre os campos preenchidos e os %LN recebem um repórter List.Var) */ static bool model_fits(const Model* m, const TbBpTab* tab, int bi) { if (m->import_only) return false; const TbBpBlock* b = &tab->blocks[bi]; bool covered[TB_BP_MAX_INPUTS] = {0}; for (int i = 0; i < m->n; i++) { int s = m->slot[i]; if (s < 0 || s >= TB_BP_MAX_INPUTS) continue; covered[s] = true; if (m->listslot[i]) { int c = b->args[s]; if (c < 0 || strcmp(tab->blocks[c].type, "List.Var") != 0 || tab->blocks[c].args[0] >= 0) return false; } } for (int s = 0; s < TB_BP_MAX_INPUTS; s++) if (!covered[s] && slot_used(tab, bi, s)) return false; return true; } static void render_block(const Models* M, const TbBpTab* tab, int bi, Sb* out, bool outer); /* Valor de um campo, no parentese pedido pelo modelo ('(' '[' '<') */ static void render_slot(const Models* M, const TbBpTab* tab, int bi, int s, int kind, bool dropdown, Sb* out) { const TbBpBlock* b = &tab->blocks[bi]; int c = s < TB_BP_MAX_INPUTS ? b->args[s] : -1; if (c >= 0 && is_literal(tab->blocks[c].type)) { const TbBpBlock* L = &tab->blocks[c]; const char* v = strcmp(L->type, "Literal.Text") == 0 && L->lit[0] ? L->lit : L->in_text[0]; sb_str(out, kind == T_ROUND ? "(" : "["); sb_esc(out, v); sb_str(out, kind == T_ROUND ? ")" : "]"); 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; } sb_str(out, kind == T_ROUND ? "(" : "["); sb_esc(out, v); if (dropdown) sb_str(out, " v"); sb_str(out, kind == T_ROUND ? ")" : "]"); } static void render_tokens(const Models* M, const Model* m, const TbBpTab* tab, int bi, Sb* out) { for (int i = 0; i < m->n; i++) { if (i) sb_str(out, " "); const Tok* t = &m->tok[i]; int s = m->slot[i]; if (s >= 0 && m->listslot[i]) { /* nome da lista, como menu */ int c = tab->blocks[bi].args[s]; sb_str(out, "["); sb_esc(out, c >= 0 ? tab->blocks[c].in_text[0] : ""); sb_str(out, " v]"); continue; } if (s >= 0) { int kind = t->kind; if (kind == T_WORD) { /* "%1" solto (rotulo do chamador) */ int sk = M->cx && M->cx->slot_kind ? M->cx->slot_kind(m->type, s, M->cx->ud) : TB_SB_SLOT_TEXT; kind = sk == TB_SB_SLOT_BOOL ? T_ANGLE : sk == TB_SB_SLOT_NUM ? T_ROUND : T_SQUARE; } render_slot(M, tab, bi, s, kind, t->dropdown, out); continue; } switch (t->kind) { case T_ROUND: sb_str(out, "("); sb_esc(out, t->text); sb_str(out, ")"); break; case T_SQUARE: sb_str(out, "["); sb_esc(out, t->text); sb_str(out, t->dropdown ? " v]" : "]"); break; case T_ANGLE: sb_str(out, "<"); sb_str(out, t->text); sb_str(out, ">"); break; default: sb_str(out, t->text); break; } } } /* Texto de um bloco; outer = com os parenteses de repórter/booleano */ static void render_block(const Models* M, const TbBpTab* tab, int bi, Sb* out, bool outer) { const TbBpBlock* b = &tab->blocks[bi]; int sh = block_shape(M, b->type); bool rep = sh == TB_SB_REPORTER, boo = sh == TB_SB_BOOLEAN; if (outer && rep) sb_str(out, "("); 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 (is_literal(b->type)) { sb_esc(out, strcmp(b->type, "Literal.Text") == 0 && b->lit[0] ? b->lit : b->in_text[0]); } else { const Model* use = NULL; for (int i = 0; i < M->n && !use; i++) if (M->m[i].builtin && !strcmp(M->m[i].type, b->type) && model_fits(&M->m[i], tab, bi)) use = &M->m[i]; for (int i = 0; i < M->n && !use; i++) if (!M->m[i].builtin && !strcmp(M->m[i].type, b->type)) use = &M->m[i]; if (use) { render_tokens(M, use, tab, bi, out); if (use->builtin && use->cat[0]) { sb_str(out, " :: "); sb_str(out, use->cat); } if (!use->builtin) { /* bloco so do TinyBlocks */ const char* cat = M->cx && M->cx->category ? M->cx->category(b->type, M->cx->ud) : NULL; sb_str(out, " :: "); sb_str(out, cat && cat[0] ? cat : "extension"); } } else { /* sem modelo: o nome do tipo e os campos */ sb_str(out, b->type); for (int s = 0; s < TB_BP_MAX_INPUTS; s++) { if (!slot_used(tab, bi, s)) continue; sb_str(out, " "); render_slot(M, tab, bi, s, T_SQUARE, false, out); } sb_str(out, " :: extension"); } } if (outer && rep) sb_str(out, ")"); if (outer && boo) sb_str(out, ">"); } static void indent(Sb* out, int depth) { for (int i = 0; i < depth; i++) sb_str(out, " "); } static void render_chain(const Models* M, const TbBpTab* tab, int bi, int depth, Sb* out) { for (int c = bi; c >= 0 && c < TB_BP_MAX_WS && tab->blocks[c].used; c = tab->blocks[c].next) { const TbBpBlock* b = &tab->blocks[c]; int sh = block_shape(M, b->type); indent(out, depth); render_block(M, tab, c, out, true); sb_str(out, "\n"); if (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) { render_chain(M, tab, b->sub[0], depth + 1, out); if (sh == TB_SB_C2) { indent(out, depth); sb_str(out, "else\n"); render_chain(M, tab, b->sub[1], depth + 1, out); } indent(out, depth); sb_str(out, "end\n"); } } } char* tb_scratchblocks_export(const TbBpTab* tab, const TbSbContext* cx) { if (!tab) return NULL; Models M = models_load(cx); if (!M.m) return NULL; /* pilhas de cima para baixo */ int order[TB_BP_MAX_WS], n = 0; for (int i = 0; i < tab->top_n; i++) { int bi = tab->top[i]; if (bi < 0 || bi >= TB_BP_MAX_WS || !tab->blocks[bi].used) continue; int k = n++; while (k > 0 && tab->blocks[order[k - 1]].y > tab->blocks[bi].y) { order[k] = order[k - 1]; k--; } order[k] = bi; } Sb out = {0}; sb_str(&out, ""); for (int i = 0; i < n; i++) { if (i) sb_str(&out, "\n"); render_chain(&M, tab, order[i], 0, &out); } free(M.m); return out.p; } /* -- Importar -------------------------------------------------------------- */ typedef struct { const Models* M; TbBpTab* tab; char* warn; size_t warn_cap; int line; } Imp; static void imp_warn(Imp* I, const char* what, const char* text) { if (!I->warn || I->warn[0]) return; snprintf(I->warn, I->warn_cap, "linha %d: %s: %.120s", I->line, what, text); } static bool is_number(const char* s) { if (!*s) return true; char* e; strtod(s, &e); while (*e == ' ') e++; return *e == 0; } static int new_block(Imp* I, const char* type) { int bi = tb_blueprint_alloc_block(I->tab); if (bi < 0) { imp_warn(I, "limite de blocos", type); return -1; } snprintf(I->tab->blocks[bi].type, sizeof(I->tab->blocks[bi].type), "%s", type); return bi; } static int parse_inner(Imp* I, const char* text, char cls); /* Preenche o campo s do bloco bi com o token t */ static void fill_slot(Imp* I, int bi, int s, const Tok* t, bool listslot) { if (s < 0 || s >= TB_BP_MAX_INPUTS) return; TbBpBlock* b = &I->tab->blocks[bi]; if (listslot) { /* [nome v] -> lista com nome */ int c = new_block(I, "List.Var"); if (c < 0) return; snprintf(I->tab->blocks[c].in_text[0], 64, "%.63s", t->text); tb_blueprint_link(I->tab, bi, TB_BP_REL_ARG0 + s, c); return; } if (t->kind == T_SQUARE || (t->kind == T_ROUND && is_number(t->text))) { snprintf(b->in_text[s], sizeof(b->in_text[s]), "%.63s", t->text); return; } if (!t->text[0]) return; /* <> vazio */ int c = parse_inner(I, t->text, t->kind == T_ANGLE ? 'b' : 'r'); if (c >= 0) tb_blueprint_link(I->tab, bi, TB_BP_REL_ARG0 + s, c); } /* Cria o bloco do modelo m a partir dos tokens */ static int build_from(Imp* I, const Model* m, const Tok* t, int n) { int bi = new_block(I, m->type); if (bi < 0) return -1; for (int i = 0; i < n; i++) if (m->slot[i] >= 0) fill_slot(I, bi, m->slot[i], &t[i], m->listslot[i]); return bi; } /* Procura o modelo para tokens de uma classe: 's' comando, 'r', 'b' */ static const Model* find_model(const Models* M, const Tok* t, int n, char cls) { for (int pass = 0; pass < 2; pass++) for (int i = 0; i < M->n; i++) { const Model* m = &M->m[i]; bool ok = cls == 's' ? shape_is_stmt(m->shape) : pass == 0 ? m->shape == cls : (m->shape == 'r' || m->shape == 'b'); if (ok && model_match(m, t, n)) return m; } return NULL; } /* Conteudo de um ( ) ou < > -> repórter */ static int parse_inner(Imp* I, const char* text, char cls) { char buf[TOK_TEXT]; snprintf(buf, sizeof(buf), "%s", text); strip_category(buf); Tok t[TOK_MAX]; int n = tokenize(buf, t, TOK_MAX); if (n < 0) { imp_warn(I, "parenteses nao fecham", text); return -1; } const Model* m = find_model(I->M, t, n, cls); if (m) return build_from(I, m, t, n); bool words = n > 0; for (int i = 0; i < n; i++) if (t[i].kind != T_WORD) words = false; 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); return bi; } imp_warn(I, "repórter desconhecido", text); return -1; } /* Tira comentario "// ..." (fora de colchetes) e espacos das pontas */ static void clean_line(char* s) { for (int k = 0; s[k]; ) { if (s[k] == '\\' && s[k + 1]) { k += 2; continue; } if (s[k] == '(' || s[k] == '[' || s[k] == '<') { k = skip_group(s, k); continue; } if (s[k] == '/' && s[k + 1] == '/') { s[k] = 0; break; } k++; } char* p = s; while (*p == ' ' || *p == '\t') p++; if (p != s) memmove(s, p, strlen(p) + 1); int n = (int)strlen(s); while (n > 0 && (s[n - 1] == ' ' || s[n - 1] == '\t' || s[n - 1] == '\r')) s[--n] = 0; } typedef struct { int cblock, sub, last; } Level; #define LEVEL_MAX 32 int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* cx, 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 }; Level lv[LEVEL_MAX]; int depth = 0, stacks = 0; lv[0].cblock = -1; lv[0].sub = 0; lv[0].last = -1; float y = 40; const char* p = text; while (*p) { const char* e = strchr(p, '\n'); size_t len = e ? (size_t)(e - p) : strlen(p); char line[1024]; if (len >= sizeof(line)) len = sizeof(line) - 1; memcpy(line, p, len); line[len] = 0; p = e ? e + 1 : p + len; I.line++; 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; continue; } if (!strcasecmp(line, "end")) { if (depth > 0) depth--; continue; } if (!strcasecmp(line, "else")) { if (depth > 0) { TbBpBlock* c = &out->blocks[lv[depth].cblock]; if (!strcmp(c->type, "Control.If")) snprintf(c->type, sizeof(c->type), "Control.IfElse"); lv[depth].sub = 1; lv[depth].last = -1; } continue; } char body[1024]; snprintf(body, sizeof(body), "%s", line); /* repórter/booleano solto numa linha */ char outer = 0; size_t bl = strlen(body); if (bl >= 2 && ((body[0] == '(' && group_end(body, 0) == (int)bl - 1) || (body[0] == '<' && group_end(body, 0) == (int)bl - 1))) { outer = body[0] == '(' ? 'r' : 'b'; body[bl - 1] = 0; memmove(body, body + 1, bl); } int bi; const Model* m = NULL; if (outer) { bi = parse_inner(&I, body, outer); } else { strip_category(body); Tok t[TOK_MAX]; int n = tokenize(body, t, TOK_MAX); if (n < 0) { imp_warn(&I, "parenteses nao fecham", line); continue; } m = find_model(&M, t, n, 's'); if (!m) { imp_warn(&I, "bloco desconhecido", line); continue; } bi = build_from(&I, m, t, n); } if (bi < 0) continue; int sh = block_shape(&M, out->blocks[bi].type); int prev = lv[depth].last; 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 */ depth = 0; out->blocks[bi].x = 40; out->blocks[bi].y = y; y += 120; tb_blueprint_top_add(out, bi); stacks++; lv[0].last = outer ? -1 : bi; } else { Level* L = &lv[depth]; if (L->last >= 0) tb_blueprint_link(out, L->last, TB_BP_REL_NEXT, bi); else if (depth > 0) tb_blueprint_link(out, L->cblock, TB_BP_REL_SUB0 + L->sub, bi); L->last = bi; } if (!outer && (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) && depth + 1 < LEVEL_MAX) { depth++; lv[depth].cblock = bi; lv[depth].sub = 0; lv[depth].last = -1; } } free(M.m); return stacks; }