/* * TinyBlocks - tb_syntax.c * Categoria "Sintaxe": Syntax.Highlight / Syntax.Languages / Syntax.Color. * Tokenizador simples (keyword/string/comment/number/preproc/punct) que * devolve o texto colorido em XML. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include "tb_syntax.h" static char s_err[160] = ""; const char* tb_syntax_last_error(void) { return s_err; } /* --- Buffer */ typedef struct { char* p; size_t n, cap; } Buf; static bool b_reserve(Buf* b, size_t extra) { if (b->n + extra + 1 <= b->cap) return true; size_t cap = b->cap ? b->cap : 128; while (cap < b->n + extra + 1) cap *= 2; char* p = (char*)realloc(b->p, cap); if (!p) return false; b->p = p; b->cap = cap; return true; } static bool b_raw(Buf* b, const char* s, size_t n) { if (!b_reserve(b, n)) return false; memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; return true; } static bool b_str(Buf* b, const char* s) { return b_raw(b, s, strlen(s)); } static bool b_ch(Buf* b, char c) { return b_raw(b, &c, 1); } static void b_esc(Buf* b, const char* s, size_t n) { for (size_t i = 0; i < n; i++) { char c = s[i]; if (c == '&') b_str(b, "&"); else if (c == '<') b_str(b, "<"); else if (c == '>') b_str(b, ">"); else b_ch(b, c); } } /* --- Token tip */ typedef enum { T_PLAIN, T_KW, T_TYPE, T_STR, T_NUM, T_CMT, T_PRE, T_FN, T_OP, T_PUNC, T_ID } TK; static const char* tk_name(TK k) { switch (k) { case T_KW: return "kw"; case T_TYPE: return "type"; case T_STR: return "str"; case T_NUM: return "num"; case T_CMT: return "cmt"; case T_PRE: return "pre"; case T_FN: return "fn"; case T_OP: return "op"; case T_PUNC: return "punc"; case T_ID: return "id"; default: return "plain"; } } static const char* tk_color(TK k) { switch (k) { case T_KW: return "#c678dd"; case T_TYPE: return "#e5c07b"; case T_STR: return "#98c379"; case T_NUM: return "#d19a66"; case T_CMT: return "#7f848e"; case T_PRE: return "#e06c75"; case T_FN: return "#61afef"; case T_OP: return "#56b6c2"; case T_PUNC: return "#abb2bf"; case T_ID: return "#9cdcfe"; default: return "#d4d4d4"; } } const char* tb_syntax_type_color(const char* type) { if (!type) return tk_color(T_PLAIN); if (!strcmp(type, "kw")) return tk_color(T_KW); if (!strcmp(type, "type")) return tk_color(T_TYPE); if (!strcmp(type, "str")) return tk_color(T_STR); if (!strcmp(type, "num")) return tk_color(T_NUM); if (!strcmp(type, "cmt")) return tk_color(T_CMT); if (!strcmp(type, "pre")) return tk_color(T_PRE); if (!strcmp(type, "fn")) return tk_color(T_FN); if (!strcmp(type, "op")) return tk_color(T_OP); if (!strcmp(type, "punc")) return tk_color(T_PUNC); if (!strcmp(type, "id")) return tk_color(T_ID); return tk_color(T_PLAIN); } /* --- Linguagens */ typedef struct { const char* name; const char* aliases; /* separados por espaco */ const char* line_cmt; /* NULL = nenhum */ bool block_cmt; /* C-style */ bool preproc; /* '#' no inicio da linha */ bool quotes; /* ' e " */ const char* keywords; const char* types; const char* builtins; } Lang; #define KW_C \ "auto break case const continue default do else enum extern for goto if " \ "inline register restrict return sizeof static struct switch typedef " \ "union volatile while _Bool _Static_assert" #define TY_C \ "char double float int long short signed unsigned void size_t ssize_t " \ "int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t uint64_t " \ "uintptr_t ptrdiff_t bool FILE va_list" #define BI_C \ "printf fprintf sprintf snprintf malloc calloc realloc free memcpy memset " \ "strlen strcmp strcpy memmove abs fabs sqrt pow sin cos floor ceil fopen " \ "fclose fread fwrite fgets fputs remove rename" #define KW_PY \ "and as assert async await break class continue def del elif else except " \ "finally for from global if import in is lambda nonlocal not or pass raise " \ "return try while with yield" #define TY_PY \ "int float complex bool str bytes list tuple dict set frozenset object " \ "type None True False self" #define BI_PY \ "print len range str int float list dict set tuple sum min max abs open " \ "enumerate zip map filter sorted type isinstance getattr setattr append" #define KW_JS \ "var let const function return if else for while do break continue class " \ "new delete typeof instanceof in of this super extends import export from " \ "default try catch finally throw async await yield switch case null " \ "undefined true false" #define TY_JS \ "Object Array String Number Boolean Symbol Promise Map Set Date RegExp" #define BI_JS \ "console log alert parseInt parseFloat JSON stringify require" #define KW_TOML "true false" #define KW_MD "" static Lang L_C = { "c", "c h cpp cc cxx hpp c++ objc", "//", true, true, true, KW_C, TY_C, BI_C }; static Lang L_PY = { "python", "py python python3", "#", false, false, true, KW_PY, TY_PY, BI_PY }; static Lang L_JS = { "javascript", "js javascript mjs node", "//", true, false, true, KW_JS, TY_JS, BI_JS }; static Lang L_JSON = { "json", "json", NULL, false, false, true, "true false null", "", "" }; static Lang L_TOML = { "toml", "toml ini cfg", "#", false, false, true, KW_TOML, "", "" }; static Lang L_XML = { "xml", "xml html htm svg xhtml", NULL, true, false, true, "", "", "" }; static Lang L_MD = { "markdown", "md markdown mkd", NULL, false, false, true, KW_MD, "", "" }; static Lang L_TXT = { "texto", "txt text plain log", NULL, false, false, false, "", "", "" }; static Lang* LANGS[] = { &L_C, &L_PY, &L_JS, &L_JSON, &L_TOML, &L_XML, &L_MD, &L_TXT }; #define NLANGS ((int)(sizeof(LANGS)/sizeof(LANGS[0]))) int tb_syntax_language_count(void) { return NLANGS; } const char* tb_syntax_language_name(int i) { if (i < 0 || i >= NLANGS) return "texto"; return LANGS[i]->name; } const char* tb_syntax_normalize_lang(const char* lang) { if (!lang || !*lang) return "texto"; /* Aceita nome de linguagem ou caminho com extensao: usa o que vem * depois do ultimo '.'. */ const char* src = lang; const char* dot = strrchr(lang, '.'); if (dot && dot[1]) src = dot + 1; char buf[32]; size_t n = 0; for (const char* p = src; *p && n < sizeof(buf)-1; p++) buf[n++] = (char)tolower((unsigned char)*p); buf[n] = 0; if (!buf[0]) return "texto"; for (int i = 0; i < NLANGS; i++) { const char* a = LANGS[i]->aliases; size_t al = strlen(LANGS[i]->name); for (const char* p = a; p && *p; ) { while (*p == ' ') p++; const char* s = p; while (*p && *p != ' ') p++; size_t l = (size_t)(p - s); if (l == n && !strncmp(s, buf, l)) return LANGS[i]->name; } if (al == n && !strncmp(LANGS[i]->name, buf, n)) return LANGS[i]->name; } return "texto"; } static Lang* lang_find(const char* lang) { const char* nm = tb_syntax_normalize_lang(lang); for (int i = 0; i < NLANGS; i++) if (!strcmp(LANGS[i]->name, nm)) return LANGS[i]; return &L_TXT; } static bool word_in(const char* list, const char* w, size_t n) { if (!list || !*list) return false; const char* p = list; while (*p) { while (*p == ' ') p++; const char* s = p; while (*p && *p != ' ') p++; if ((size_t)(p - s) == n && !strncmp(s, w, n)) return true; } return false; } /* --- Emissao */ static bool emit(Buf* b, TK k, const char* s, size_t n, bool inline_mode) { (void)inline_mode; if (n == 0) return true; b_str(b, ""); b_esc(b, s, n); b_str(b, ""); return true; } /* --- Tokenizadores */ static bool is_id_start(int c) { return isalpha(c) || c == '_'; } static bool is_id_char(int c) { return isalnum(c) || c == '_'; } static bool is_op(int c) { return strchr("+-*/%=!<>&|^~?:.", c) != NULL; } static bool is_punc(int c) { return strchr("(){}[];,@", c) != NULL; } static void tok_c_like(Buf* b, const char* s, Lang* L, bool inline_mode) { size_t i = 0, n = strlen(s); bool line_start = true; while (i < n) { char c = s[i]; if (c == '\n') { b_ch(b, '\n'); i++; line_start = true; continue; } if (c == ' ' || c == '\t' || c == '\r') { b_ch(b, c); i++; continue; } if (line_start && L->preproc && c == '#') { size_t j = i; while (j < n && s[j] != '\n') j++; emit(b, T_PRE, s + i, j - i, inline_mode); i = j; line_start = false; continue; } if (L->block_cmt && c == '/' && i + 1 < n && s[i+1] == '*') { size_t j = i + 2; while (j + 1 < n && !(s[j] == '*' && s[j+1] == '/')) j++; j = (j + 1 < n) ? j + 2 : n; emit(b, T_CMT, s + i, j - i, inline_mode); i = j; line_start = false; continue; } if (L->line_cmt && !strncmp(s + i, L->line_cmt, strlen(L->line_cmt))) { size_t j = i; while (j < n && s[j] != '\n') j++; emit(b, T_CMT, s + i, j - i, inline_mode); i = j; continue; } if (c == '"' || (L->quotes && c == '\'')) { char q = c; size_t j = i + 1; while (j < n && s[j] != q) { if (s[j] == '\\' && j + 1 < n) j++; j++; } if (j < n) j++; emit(b, T_STR, s + i, j - i, inline_mode); i = j; line_start = false; continue; } if (isdigit((unsigned char)c) || (c == '.' && i + 1 < n && isdigit((unsigned char)s[i+1]))) { size_t j = i; while (j < n && (isalnum((unsigned char)s[j]) || s[j] == '.' || s[j] == '_' || s[j] == 'x' || s[j] == 'X')) j++; emit(b, T_NUM, s + i, j - i, inline_mode); i = j; line_start = false; continue; } if (is_id_start((unsigned char)c)) { size_t j = i; while (j < n && is_id_char((unsigned char)s[j])) j++; size_t wl = j - i; TK k; if (word_in(L->keywords, s + i, wl)) k = T_KW; else if (word_in(L->types, s + i, wl)) k = T_TYPE; else if (word_in(L->builtins, s + i, wl)) k = T_FN; else { size_t jj = j; while (jj < n && (s[jj] == ' ' || s[jj] == '\t')) jj++; k = (jj < n && s[jj] == '(') ? T_FN : T_ID; } emit(b, k, s + i, wl, inline_mode); i = j; line_start = false; continue; } if (is_op((unsigned char)c)) { size_t j = i; while (j < n && is_op((unsigned char)s[j])) j++; emit(b, T_OP, s + i, j - i, inline_mode); i = j; line_start = false; continue; } if (is_punc((unsigned char)c)) { emit(b, T_PUNC, s + i, 1, inline_mode); i++; line_start = false; continue; } b_ch(b, c); i++; line_start = false; } } /* XML/HTML: trata tags e comentarios */ static void tok_xml(Buf* b, const char* s, bool inline_mode) { size_t i = 0, n = strlen(s); while (i < n) { if (!strncmp(s + i, "", 3)) j++; j = (j + 2 < n) ? j + 3 : n; emit(b, T_CMT, s + i, j - i, inline_mode); i = j; continue; } if (s[i] == '<') { size_t j = i; emit(b, T_PUNC, s + j, 1, inline_mode); j++; if (j < n && s[j] == '/') { emit(b, T_PUNC, s + j, 1, inline_mode); j++; } size_t ns = j; while (j < n && (isalnum((unsigned char)s[j]) || s[j] == '-' || s[j] == ':' || s[j] == '_')) j++; if (j > ns) emit(b, T_TYPE, s + ns, j - ns, inline_mode); while (j < n && s[j] != '>') { if (s[j] == '"' || s[j] == '\'') { char q = s[j]; size_t k = j + 1; while (k < n && s[k] != q) k++; if (k < n) k++; emit(b, T_STR, s + j, k - j, inline_mode); j = k; } else if (is_id_start((unsigned char)s[j])) { size_t k = j; while (k < n && is_id_char((unsigned char)s[k])) k++; emit(b, T_ID, s + j, k - j, inline_mode); j = k; } else if (s[j] == '=' || s[j] == '/') { emit(b, T_OP, s + j, 1, inline_mode); j++; } else if (s[j] == ' ' || s[j] == '\t' || s[j] == '\n') { b_ch(b, s[j]); j++; } else { b_ch(b, s[j]); j++; } } if (j < n) { emit(b, T_PUNC, s + j, 1, inline_mode); j++; } i = j; continue; } if (s[i] == '&') { size_t j = i + 1; while (j < n && s[j] != ';' && j - i < 12) j++; if (j < n && s[j] == ';') j++; emit(b, T_NUM, s + i, j - i, inline_mode); i = j; continue; } b_ch(b, s[i]); i++; } } /* Markdown: titulos, listas, citacoes, codigo, links, enfase. */ static void tok_md(Buf* b, const char* s, bool inline_mode) { size_t i = 0, n = strlen(s); bool bol = true; while (i < n) { if (s[i] == '\n') { b_ch(b, '\n'); i++; bol = true; continue; } if (bol) { if (s[i] == '#') { size_t j = i; while (j < n && s[j] == '#') j++; emit(b, T_KW, s + i, j - i, inline_mode); size_t k = j; while (k < n && s[k] != '\n') k++; emit(b, T_TYPE, s + j, k - j, inline_mode); i = k; bol = false; continue; } if (s[i] == '>' || s[i] == '-' || s[i] == '*' || s[i] == '+') { size_t j = i; while (j < n && (s[j] == s[i] || s[j] == ' ')) j++; emit(b, T_OP, s + i, j - i, inline_mode); i = j; bol = false; continue; } if (isdigit((unsigned char)s[i])) { size_t j = i; while (j < n && (isdigit((unsigned char)s[j]) || s[j] == '.' || s[j] == ')')) j++; emit(b, T_OP, s + i, j - i, inline_mode); i = j; bol = false; continue; } bol = false; } if (s[i] == '`') { size_t j = i + 1; while (j < n && s[j] != '`' && s[j] != '\n') j++; if (j < n && s[j] == '`') j++; emit(b, T_STR, s + i, j - i, inline_mode); i = j; continue; } if (s[i] == '*' || s[i] == '_') { size_t j = i; while (j < n && (s[j] == '*' || s[j] == '_')) j++; emit(b, T_OP, s + i, j - i, inline_mode); i = j; continue; } if (s[i] == '[') { size_t j = i; int depth = 0; while (j < n && s[j] != '\n') { if (s[j] == '[') depth++; else if (s[j] == ']') { depth--; if (depth == 0) { j++; break; } } j++; } emit(b, T_FN, s + i, j - i, inline_mode); i = j; continue; } b_ch(b, s[i]); i++; } } /* --- Render */ char* tb_syntax_highlight_inline(const char* text, const char* lang) { s_err[0] = 0; if (!text) text = ""; Lang* L = lang_find(lang); /* inline: uma unica linha (quebras viram espacos) */ char* tmp = (char*)malloc(strlen(text) + 1); if (!tmp) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; } size_t k = 0; for (const char* p = text; *p; p++) tmp[k++] = (*p == '\n') ? ' ' : *p; tmp[k] = 0; Buf b = {0}; if (L == &L_XML) tok_xml(&b, tmp, true); else if (L == &L_MD) tok_md(&b, tmp, true); else tok_c_like(&b, tmp, L, true); free(tmp); return b.p; } char* tb_syntax_highlight(const char* text, const char* lang) { s_err[0] = 0; /* divide por linhas e tokeniza cada uma (tokenizador pede string terminada) */ Lang* L = lang_find(lang); Buf b = {0}; char hdr[96]; snprintf(hdr, sizeof(hdr), "\n", L->name); b_str(&b, hdr); const char* p = text ? text : ""; size_t n = strlen(p); size_t i = 0; while (i <= n) { const char* nl = strchr(p + i, '\n'); size_t len = nl ? (size_t)(nl - (p + i)) : n - i; char* line = (char*)malloc(len + 1); if (!line) { free(b.p); snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; } memcpy(line, p + i, len); line[len] = 0; b_str(&b, ""); if (L == &L_XML) tok_xml(&b, line, false); else if (L == &L_MD) tok_md(&b, line, false); else tok_c_like(&b, line, L, false); b_str(&b, "\n"); free(line); if (!nl) break; i = (size_t)(nl - p) + 1; } b_str(&b, ""); return b.p; } /* --- Blocos */ static void eval_highlight(TinyBlocks_Block* self, TinyBlocks* rt) { char* x = tb_syntax_highlight(tb_block_input_text(self, rt, 0), tb_block_input_text(self, rt, 1)); tb_block_set_output(self, 0, tb_value_text(x ? x : "")); free(x); self->dirty = false; } static void eval_inline(TinyBlocks_Block* self, TinyBlocks* rt) { char* x = tb_syntax_highlight_inline(tb_block_input_text(self, rt, 0), tb_block_input_text(self, rt, 1)); tb_block_set_output(self, 0, tb_value_text(x ? x : "")); free(x); self->dirty = false; } static void eval_languages(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; Buf b = {0}; for (int i = 0; i < NLANGS; i++) { if (i) b_str(&b, ", "); b_str(&b, LANGS[i]->name); } tb_block_set_output(self, 0, tb_value_text(b.p ? b.p : "")); free(b.p); self->dirty = false; } 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, void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); return t && tb_library_add(lib, &t->base); } static bool syntax_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_Category cat = { "Sintaxe", { 255/255.f, 152/255.f, 0/255.f, 1.f}, { 230/255.f, 119/255.f, 0/255.f, 1.f}, }; tb_library_set_category(lib, &cat); /* Metadados dos blocos (tooltip do editor: Alt + hover). */ TB_BLOCK_META("Syntax.Highlight", "eval_highlight", "Realca a sintaxe de um texto (XML)"); TB_BLOCK_META("Syntax.Inline", "eval_inline", "Realca uma unica linha de codigo (XML)"); TB_BLOCK_META("Syntax.Languages", "eval_languages", "Lista as linguagens suportadas"); static const TinyBlocks_SlotDesc hl_in[] = {{"texto", TB_VALUE_TEXT}, {"linguagem", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc out_text_s[] = {{"xml", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc out_list_s[] = {{"linguagens", TB_VALUE_TEXT}}; return reg(rt, lib, "Syntax.Highlight", hl_in, 2, out_text_s, 1, eval_highlight) && reg(rt, lib, "Syntax.Inline", hl_in, 2, out_text_s, 1, eval_inline) && reg(rt, lib, "Syntax.Languages", NULL, 0, out_list_s, 1, eval_languages); } TINYBLOCKS_DEFINE_LIBRARY(syntax, "tinyblocks-syntax", "1.0.0", syntax_init, NULL) const TinyBlocks_LibraryDescriptor* tb_syntax_get_library(void) { return &_tb_lib_desc_syntax; }