From a921f6574dd1a6630d1737c6cd99a504a53a79dd Mon Sep 17 00:00:00 2001 From: mguinhos Date: Tue, 20 Oct 2026 22:04:09 -0300 Subject: [PATCH] Adiciona tinyblocks-syntax, tinyblocks-regex e tinyblocks-markdown (com testes) --- Makefile | 62 ++- libraries/tinyblocks-markdown/Makefile | 28 + .../tinyblocks-markdown/include/tb_markdown.h | 23 + libraries/tinyblocks-markdown/library.toml | 15 + .../tinyblocks-markdown/src/tb_markdown.c | 517 ++++++++++++++++++ libraries/tinyblocks-regex/Makefile | 28 + libraries/tinyblocks-regex/include/tb_regex.h | 40 ++ libraries/tinyblocks-regex/library.toml | 15 + libraries/tinyblocks-regex/src/tb_regex.c | 318 +++++++++++ libraries/tinyblocks-syntax/Makefile | 28 + .../tinyblocks-syntax/include/tb_syntax.h | 43 ++ libraries/tinyblocks-syntax/library.toml | 15 + libraries/tinyblocks-syntax/src/tb_syntax.c | 499 +++++++++++++++++ tests/markdown_test.c | 87 +++ tests/regex_test.c | 68 +++ tests/syntax_test.c | 64 +++ 16 files changed, 1846 insertions(+), 4 deletions(-) create mode 100644 libraries/tinyblocks-markdown/Makefile create mode 100644 libraries/tinyblocks-markdown/include/tb_markdown.h create mode 100644 libraries/tinyblocks-markdown/library.toml create mode 100644 libraries/tinyblocks-markdown/src/tb_markdown.c create mode 100644 libraries/tinyblocks-regex/Makefile create mode 100644 libraries/tinyblocks-regex/include/tb_regex.h create mode 100644 libraries/tinyblocks-regex/library.toml create mode 100644 libraries/tinyblocks-regex/src/tb_regex.c create mode 100644 libraries/tinyblocks-syntax/Makefile create mode 100644 libraries/tinyblocks-syntax/include/tb_syntax.h create mode 100644 libraries/tinyblocks-syntax/library.toml create mode 100644 libraries/tinyblocks-syntax/src/tb_syntax.c create mode 100644 tests/markdown_test.c create mode 100644 tests/regex_test.c create mode 100644 tests/syntax_test.c diff --git a/Makefile b/Makefile index 7b752ab..5026aa6 100644 --- a/Makefile +++ b/Makefile @@ -33,6 +33,10 @@ IMG_DIR := $(LIBDIR)/tinyblocks-image VG_DIR := $(LIBDIR)/tinyblocks-vg SVG_DIR := $(LIBDIR)/tinyblocks-svg JPG_DIR := $(LIBDIR)/tinyblocks-jpg +SYN_DIR := $(LIBDIR)/tinyblocks-syntax +RE_DIR := $(LIBDIR)/tinyblocks-regex +MD_DIR := $(LIBDIR)/tinyblocks-markdown +OT_DIR := $(LIBDIR)/tinyblocks-opentype API_DIR := $(LIBDIR)/tinyblocks-api LIBM_DIR := $(LIBDIR)/tinyblocks-libman ED_DIR := $(LIBDIR)/tinyblocks-editor @@ -89,11 +93,12 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ appdir appimage run-appimage icon \ test-toml test-plugin test-blueprint test-base64 test-curves test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ + test-syntax test-regex test-markdown test-opentype \ category-libs category-sos libs \ lib-events lib-control lib-operators lib-variables lib-appearance lib-pen lib-fs \ lib-environ \ lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-api lib-libman \ + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman \ test-libman test-environ all: static example ## Compila a biblioteca estática e o exemplo hello (padrão) @@ -196,6 +201,18 @@ lib-svg: lib-vg lib-base64 lib-jpg: $(MAKE) -C $(JPG_DIR) +lib-syntax: + $(MAKE) -C $(SYN_DIR) + +lib-regex: + $(MAKE) -C $(RE_DIR) + +lib-markdown: + $(MAKE) -C $(MD_DIR) + +lib-opentype: + $(MAKE) -C $(OT_DIR) + lib-api: $(MAKE) -C $(API_DIR) @@ -216,8 +233,8 @@ lib-mcp: libs: static lib-events lib-control lib-operators lib-variables \ lib-appearance lib-pen lib-fs lib-environ lib-graphics lib-sdl2 lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-api lib-libman lib-editor - @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + api + libman + editor" + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-bmp lib-png lib-image lib-vg lib-svg lib-jpg lib-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman lib-editor + @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + bmp + png + image + vg + svg + jpg + syntax + regex + markdown + opentype + api + libman + editor" category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so) @echo "Build category libs OK" @@ -510,6 +527,10 @@ test-bmp: $(BUILD)/bmp_test ## Roda o teste da bmp (ASan/UBSan) # -- Teste da library png (libpng) --- PNG_CFLAGS := $(shell pkg-config --cflags libpng 2>/dev/null) PNG_LIBS := $(shell pkg-config --libs libpng 2>/dev/null) + +FREETYPE_CFLAGS := $(shell pkg-config --cflags freetype2 2>/dev/null) +FREETYPE_LIBS := $(shell pkg-config --libs freetype2 2>/dev/null) +EXTRA_TEST_LIBS := $(BUILD)/png_test: tests/png_test.c $(PNG_DIR)/src/tb_png.c static @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) $(PNG_CFLAGS) -I$(PNG_DIR)/include $(PNG_DIR)/src/tb_png.c \ @@ -551,6 +572,39 @@ $(BUILD)/svg_test: tests/svg_test.c $(SVG_DIR)/src/tb_svg.c $(VG_DIR)/src/tb_vg. test-svg: $(BUILD)/svg_test ## Roda o teste da svg (ASan/UBSan) ./$(BUILD)/svg_test +# -- Testes das libraries de texto/sintaxe ------------------------------- +$(BUILD)/syntax_test: tests/syntax_test.c $(SYN_DIR)/src/tb_syntax.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(SYN_DIR)/include $(SYN_DIR)/src/tb_syntax.c tests/syntax_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group $(EXTRA_TEST_LIBS) + +test-syntax: $(BUILD)/syntax_test ## Roda o teste da syntax (ASan/UBSan) + ./$(BUILD)/syntax_test + +$(BUILD)/regex_test: tests/regex_test.c $(RE_DIR)/src/tb_regex.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(RE_DIR)/include $(RE_DIR)/src/tb_regex.c tests/regex_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group $(EXTRA_TEST_LIBS) + +test-regex: $(BUILD)/regex_test ## Roda o teste da regex (ASan/UBSan) + ./$(BUILD)/regex_test + +$(BUILD)/markdown_test: tests/markdown_test.c $(MD_DIR)/src/tb_markdown.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(MD_DIR)/include $(MD_DIR)/src/tb_markdown.c tests/markdown_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group $(EXTRA_TEST_LIBS) + +test-markdown: $(BUILD)/markdown_test ## Roda o teste da markdown (ASan/UBSan) + ./$(BUILD)/markdown_test + +$(BUILD)/opentype_test: tests/opentype_test.c $(OT_DIR)/src/tb_opentype.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(OT_DIR)/include $(OT_DIR)/src/tb_opentype.c tests/opentype_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group $(FREETYPE_LIBS) $(EXTRA_TEST_LIBS) + +test-opentype: $(BUILD)/opentype_test ## Roda o teste da opentype (ASan/UBSan) + ./$(BUILD)/opentype_test + # -- Teste da library jpg (libjpeg; pulado se os headers faltarem) --- JPG_TEST_AVAILABLE := $(shell printf '#include \nint main(void){return 0;}\n' | \ $(CC) -xc - -ljpeg -o /dev/null >/dev/null 2>&1 && echo yes) @@ -584,7 +638,7 @@ clean: ## Remove os diretórios build/ (raiz e libraries) $(RM) -r $(BUILD) @for d in $(EV_DIR) $(CT_DIR) $(OP_DIR) $(VR_DIR) $(AP_DIR) $(PN_DIR) $(FS_DIR) \ $(TOML_DIR) $(JSON_DIR) $(XML_DIR) $(CSV_DIR) $(BP_DIR) \ - $(B64_DIR) $(CV_DIR) $(PPM_DIR) $(BMP_DIR) $(PNG_DIR) $(IMG_DIR) $(VG_DIR) $(SVG_DIR) $(JPG_DIR) \ + $(B64_DIR) $(CV_DIR) $(PPM_DIR) $(BMP_DIR) $(PNG_DIR) $(IMG_DIR) $(VG_DIR) $(SVG_DIR) $(JPG_DIR) $(SYN_DIR) $(RE_DIR) $(MD_DIR) $(OT_DIR) \ $(API_DIR) $(LIBM_DIR) \ $(ED_DIR) $(GX_DIR) $(SD_DIR) $(PY_DIR) $(MC_DIR); do \ $(MAKE) -C $$d clean >/dev/null 2>&1 || true; \ diff --git a/libraries/tinyblocks-markdown/Makefile b/libraries/tinyblocks-markdown/Makefile new file mode 100644 index 0000000..4146f5d --- /dev/null +++ b/libraries/tinyblocks-markdown/Makefile @@ -0,0 +1,28 @@ +# Makefile da library markdown (categoria "Markdown") +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +OBJ := $(BUILD)/tb_markdown.o +LIB_A := $(BUILD)/libtinyblocks-markdown.a +LIB_SO := $(BUILD)/libtinyblocks-markdown.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_markdown.c include/tb_markdown.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-markdown/include/tb_markdown.h b/libraries/tinyblocks-markdown/include/tb_markdown.h new file mode 100644 index 0000000..4999da8 --- /dev/null +++ b/libraries/tinyblocks-markdown/include/tb_markdown.h @@ -0,0 +1,23 @@ +/* + * TinyBlocks - tb_markdown.h + * Library tinyblocks-markdown: converte Markdown para HTML, XML ou SVG. + * Independente do editor. + */ +#ifndef TINYBLOCKS_MARKDOWN_H +#define TINYBLOCKS_MARKDOWN_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_markdown_get_library(void); + +/* -- API C (resultados com malloc; libere com free) ---------------------- */ +TB_API char* tb_markdown_to_html(const char* md); +TB_API char* tb_markdown_to_xml(const char* md); +TB_API char* tb_markdown_to_svg(const char* md); + +/* Variante do SVG com largura/fonte configuraveis. */ +TB_API char* tb_markdown_to_svg_opts(const char* md, int width, int font_size); + +TB_API const char* tb_markdown_last_error(void); + +#endif /* TINYBLOCKS_MARKDOWN_H */ diff --git a/libraries/tinyblocks-markdown/library.toml b/libraries/tinyblocks-markdown/library.toml new file mode 100644 index 0000000..da6f440 --- /dev/null +++ b/libraries/tinyblocks-markdown/library.toml @@ -0,0 +1,15 @@ +# Metadados da library markdown. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-markdown" +version = "1.0.0" +category = "Markdown" +description = "Converte Markdown para HTML, XML ou SVG" +color = [96, 125, 139, 255] +dark = [55, 71, 79, 255] + +[build] +sources = ["src/tb_markdown.c"] +includes = ["include"] +shared = "build/libtinyblocks-markdown.so" +static = "build/libtinyblocks-markdown.a" +depends = [] diff --git a/libraries/tinyblocks-markdown/src/tb_markdown.c b/libraries/tinyblocks-markdown/src/tb_markdown.c new file mode 100644 index 0000000..ff80a18 --- /dev/null +++ b/libraries/tinyblocks-markdown/src/tb_markdown.c @@ -0,0 +1,517 @@ +/* + * TinyBlocks - tb_markdown.c + * Categoria "Markdown": Markdown.ToHtml / ToXml / ToSvg. + * + * Parser por linhas -> lista de blocos (H1..H6, paragrafo, item de lista, + * citacao, bloco de codigo, regra) -> serializacao para HTML, XML ou SVG. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include +#include "tb_markdown.h" + +static char s_err[160] = ""; +const char* tb_markdown_last_error(void) { return s_err; } + +/* ---------------------------------------------------------------- Buffer */ +typedef struct { char* p; size_t n, cap; } Buf; +static bool b_res(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_put(Buf* b, const char* s, size_t n) { + if (!b_res(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_put(b, s, strlen(s)); } +static bool b_ch(Buf* b, char c) { return b_put(b, &c, 1); } +static bool b_fmt(Buf* b, const char* f, int v) { + char tmp[48]; int n = snprintf(tmp, sizeof(tmp), f, v); + return b_put(b, tmp, (size_t)(n > 0 ? n : 0)); +} +static void b_esc(Buf* b, const char* s, size_t n) { + for (size_t i = 0; i < n; i++) { + unsigned char c = (unsigned char)s[i]; + if (c == '&') b_str(b, "&"); + else if (c == '<') b_str(b, "<"); + else if (c == '>') b_str(b, ">"); + else if (c == '"') b_str(b, """); + else b_ch(b, (char)c); + } +} + +/* ----------------------------------------------------------------- Blocos */ +typedef enum { BLK_H, BLK_P, BLK_LI, BLK_CODE, BLK_QUOTE, BLK_HR } BlkKind; +typedef struct { + BlkKind kind; + int level; /* heading */ + bool ordered; /* item de lista ordenada */ + int index; /* numero do item ordenado */ + char* text; /* conteudo (inline markdown) */ + char* lang; /* linguagem do bloco de codigo */ +} Blk; +typedef struct { Blk* v; int n, cap; } Doc; + +static Blk* doc_push(Doc* d, BlkKind k) { + if (d->n == d->cap) { + int cap = d->cap ? d->cap * 2 : 16; + Blk* v = (Blk*)realloc(d->v, (size_t)cap * sizeof(Blk)); + if (!v) return NULL; + d->v = v; d->cap = cap; + } + Blk* b = &d->v[d->n++]; + memset(b, 0, sizeof(*b)); + b->kind = k; + return b; +} +static void doc_free(Doc* d) { + for (int i = 0; i < d->n; i++) { free(d->v[i].text); free(d->v[i].lang); } + free(d->v); + d->v = NULL; d->n = d->cap = 0; +} +static char* dupn(const char* s, size_t n) { + char* p = (char*)malloc(n + 1); + if (!p) return NULL; + memcpy(p, s, n); p[n] = 0; return p; +} +static void rtrim(char* s) { size_t n = strlen(s); while (n && (s[n-1]=='\n'||s[n-1]=='\r'||s[n-1]==' '||s[n-1]=='\t')) s[--n]=0; } +static void ltrim_ptr(const char** p) { while (**p==' '||**p=='\t') (*p)++; } + +static bool hr_line(const char* s) { + int cnt = 0; char c0 = 0; + for (; *s; s++) { + if (*s == ' ' || *s == '\t') continue; + if (!c0) c0 = *s; + if (*s != c0) return false; + cnt++; + } + return cnt >= 3 && (c0 == '-' || c0 == '*' || c0 == '_'); +} + +static Doc* parse(const char* md) { + Doc* d = (Doc*)calloc(1, sizeof(Doc)); + if (!d) return NULL; + if (!md) md = ""; + const char* p = md; + bool in_code = false; + char code_lang[32] = ""; + Buf code = {0}; + Buf para = {0}; + bool para_active = false; + + #define FLUSH_PARA() do { if (para_active) { Blk* b = doc_push(d, BLK_P); if (b) { b->text = dupn(para.p ? para.p : "", para.p ? strlen(para.p) : 0); } \ + free(para.p); para.p = NULL; para.n = para.cap = 0; para_active = false; } } while (0) + + while (*p) { + const char* nl = strchr(p, '\n'); + size_t len = nl ? (size_t)(nl - p) : strlen(p); + char* line = dupn(p, len); + if (!line) break; + rtrim(line); + const char* t = line; + ltrim_ptr(&t); + + if (!in_code && !strncmp(t, "```", 3)) { + FLUSH_PARA(); + in_code = true; + const char* lang = t + 3; + ltrim_ptr(&lang); + snprintf(code_lang, sizeof(code_lang), "%s", lang); + free(line); + if (!nl) break; + p = nl + 1; + continue; + } + if (in_code) { + if (!strncmp(t, "```", 3)) { + Blk* b = doc_push(d, BLK_CODE); + if (b) { b->text = dupn(code.p ? code.p : "", code.p ? strlen(code.p) : 0); + b->lang = dupn(code_lang, strlen(code_lang)); } + free(code.p); code.p = NULL; code.n = code.cap = 0; + in_code = false; + } else { + b_put(&code, line, strlen(line)); + b_ch(&code, '\n'); + } + free(line); + if (!nl) break; + p = nl + 1; + continue; + } + + if (!*t) { FLUSH_PARA(); free(line); if (!nl) break; p = nl + 1; continue; } + + int h = 0; + while (t[h] == '#' && h < 6) h++; + if (h > 0 && (t[h] == ' ' || t[h] == 0)) { + FLUSH_PARA(); + const char* body = t + h; ltrim_ptr(&body); + Blk* b = doc_push(d, BLK_H); + if (b) { b->level = h; b->text = dupn(body, strlen(body)); } + free(line); if (!nl) break; p = nl + 1; continue; + } + if (hr_line(t)) { + FLUSH_PARA(); + doc_push(d, BLK_HR); + free(line); if (!nl) break; p = nl + 1; continue; + } + if (*t == '>') { + FLUSH_PARA(); + const char* body = t + 1; ltrim_ptr(&body); + Blk* b = doc_push(d, BLK_QUOTE); + if (b) b->text = dupn(body, strlen(body)); + free(line); if (!nl) break; p = nl + 1; continue; + } + if ((t[0] == '-' || t[0] == '*' || t[0] == '+') && (t[1] == ' ' || t[1] == 0)) { + FLUSH_PARA(); + const char* body = t + 1; ltrim_ptr(&body); + Blk* b = doc_push(d, BLK_LI); + if (b) { b->ordered = false; b->text = dupn(body, strlen(body)); } + free(line); if (!nl) break; p = nl + 1; continue; + } + if (isdigit((unsigned char)t[0])) { + const char* q = t; + while (isdigit((unsigned char)*q)) q++; + if ((*q == '.' || *q == ')') && (q[1] == ' ' || q[1] == 0)) { + FLUSH_PARA(); + const char* body = q + 1; ltrim_ptr(&body); + Blk* b = doc_push(d, BLK_LI); + if (b) { b->ordered = true; b->index = atoi(t); b->text = dupn(body, strlen(body)); } + free(line); if (!nl) break; p = nl + 1; continue; + } + } + /* paragrafo (linhas consecutivas unidas por espaco) */ + if (para_active) b_ch(¶, ' '); + b_str(¶, t); + para_active = true; + free(line); + if (!nl) break; + p = nl + 1; + } + if (in_code && code.p) { + Blk* b = doc_push(d, BLK_CODE); + if (b) b->text = dupn(code.p, strlen(code.p)); + free(code.p); code.p = NULL; + } + FLUSH_PARA(); + free(para.p); + #undef FLUSH_PARA + return d; +} + +/* ---------------------------------------------------------------- Inline */ +/* Serializa inline markdown para HTML (xml=false) ou XML (xml=true). */ +static void inline_out(Buf* b, const char* s, bool xml) { + const char* bold0 = xml ? "" : ""; + const char* bold1 = xml ? "" : ""; + const char* it0 = xml ? "" : ""; + const char* it1 = xml ? "" : ""; + while (*s) { + if (s[0] == '*' && s[1] == '*') { + const char* e = strstr(s + 2, "**"); + if (e) { + char* mid = dupn(s + 2, (size_t)(e - (s + 2))); + b_str(b, bold0); inline_out(b, mid ? mid : "", xml); b_str(b, bold1); + free(mid); s = e + 2; continue; + } + } + if (s[0] == '`') { + const char* e = strchr(s + 1, '`'); + if (e) { b_str(b, ""); b_esc(b, s + 1, (size_t)(e - (s + 1))); b_str(b, ""); s = e + 1; continue; } + } + if (s[0] == '!' && s[1] == '[') { + const char* close = strchr(s + 2, ']'); + if (close && close[1] == '(') { + const char* rp = strchr(close + 2, ')'); + if (rp) { + b_str(b, xml ? "\"");" : "\">"); + s = rp + 1; continue; + } + } + } + if (s[0] == '[') { + const char* close = strchr(s + 1, ']'); + if (close && close[1] == '(') { + const char* rp = strchr(close + 2, ')'); + if (rp) { + b_str(b, xml ? ""); + { char* mid = dupn(s + 1, (size_t)(close - (s + 1))); + inline_out(b, mid, xml); free(mid); } + b_str(b, xml ? "" : ""); + s = rp + 1; continue; + } + } + } + if ((s[0] == '*' || s[0] == '_')) { + char q = s[0]; + const char* e = strchr(s + 1, q); + if (e && e > s + 1) { + b_str(b, it0); + { char* mid = dupn(s + 1, (size_t)(e - (s + 1))); + inline_out(b, mid, xml); free(mid); } + b_str(b, it1); + s = e + 1; continue; + } + } + if (s[0] == '&') { b_str(b, "&"); s++; continue; } + if (s[0] == '<') { b_str(b, "<"); s++; continue; } + if (s[0] == '>') { b_str(b, ">"); s++; continue; } + b_ch(b, s[0]); s++; + } +} + +/* ------------------------------------------------------------------ HTML */ +char* tb_markdown_to_html(const char* md) { + s_err[0] = 0; + Doc* d = parse(md); + if (!d) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; } + Buf b = {0}; + bool in_ul = false, in_ol = false; + for (int i = 0; i < d->n; i++) { + Blk* k = &d->v[i]; + bool is_li = k->kind == BLK_LI; + if (!is_li && (in_ul || in_ol)) { + b_str(&b, in_ul ? "\n" : "\n"); in_ul = in_ol = false; + } + switch (k->kind) { + case BLK_H: + b_fmt(&b, "", k->level); inline_out(&b, k->text ? k->text : "", false); b_fmt(&b, "\n", k->level); + break; + case BLK_P: + b_str(&b, "

"); inline_out(&b, k->text ? k->text : "", false); b_str(&b, "

\n"); + break; + case BLK_QUOTE: + b_str(&b, "
"); inline_out(&b, k->text ? k->text : "", false); b_str(&b, "
\n"); + break; + case BLK_CODE: + b_str(&b, "
lang && k->lang[0]) { b_str(&b, " class=\"language-"); b_esc(&b, k->lang, strlen(k->lang)); b_str(&b, "\""); }
+            b_str(&b, ">"); b_esc(&b, k->text ? k->text : "", k->text ? strlen(k->text) : 0); b_str(&b, "
\n"); + break; + case BLK_HR: + b_str(&b, "
\n"); + break; + case BLK_LI: + if (k->ordered) { if (!in_ol) { b_str(&b, "
    \n"); in_ol = true; } } + else { if (!in_ul) { b_str(&b, "
      \n"); in_ul = true; } } + b_str(&b, "
    • "); inline_out(&b, k->text ? k->text : "", false); b_str(&b, "
    • \n"); + break; + } + } + if (in_ul) b_str(&b, "
    \n"); + if (in_ol) b_str(&b, "
\n"); + doc_free(d); free(d); + return b.p; +} + +/* ------------------------------------------------------------------- XML */ +char* tb_markdown_to_xml(const char* md) { + s_err[0] = 0; + Doc* d = parse(md); + if (!d) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; } + Buf b = {0}; + b_str(&b, "\n"); + bool in_list = false; bool list_ordered = false; + for (int i = 0; i < d->n; i++) { + Blk* k = &d->v[i]; + bool is_li = k->kind == BLK_LI; + if (!is_li && in_list) { b_str(&b, "\n"); in_list = false; } + switch (k->kind) { + case BLK_H: + b_str(&b, "level); b_str(&b, "\">"); + inline_out(&b, k->text ? k->text : "", true); b_str(&b, "\n"); + break; + case BLK_P: + b_str(&b, ""); inline_out(&b, k->text ? k->text : "", true); b_str(&b, "\n"); + break; + case BLK_QUOTE: + b_str(&b, ""); inline_out(&b, k->text ? k->text : "", true); b_str(&b, "\n"); + break; + case BLK_CODE: + b_str(&b, "lang && k->lang[0]) { b_str(&b, " lang=\""); b_esc(&b, k->lang, strlen(k->lang)); b_str(&b, "\""); } + b_str(&b, ">"); b_esc(&b, k->text ? k->text : "", k->text ? strlen(k->text) : 0); b_str(&b, "\n"); + break; + case BLK_HR: + b_str(&b, "\n"); + break; + case BLK_LI: + if (!in_list) { + b_str(&b, "ordered ? "true" : "false"); b_str(&b, "\">\n"); + in_list = true; list_ordered = k->ordered; + } + (void)list_ordered; + b_str(&b, ""); inline_out(&b, k->text ? k->text : "", true); b_str(&b, "\n"); + break; + } + } + if (in_list) b_str(&b, "\n"); + b_str(&b, ""); + doc_free(d); free(d); + return b.p; +} + +/* ------------------------------------------------------------------- SVG */ +char* tb_markdown_to_svg_opts(const char* md, int width, int font_size) { + s_err[0] = 0; + if (width < 80) width = 640; + if (font_size < 6) font_size = 16; + Doc* d = parse(md); + if (!d) { snprintf(s_err, sizeof(s_err), "sem memoria"); return NULL; } + + int pad = 16; + int line_h = (int)(font_size * 1.5); + int y = pad + font_size; + Buf body = {0}; + char num[24]; + for (int i = 0; i < d->n; i++) { + Blk* k = &d->v[i]; + int fs = font_size; + bool bold = false, mono = false, italic = false; + int indent = 0; + const char* prefix = ""; + int bullet_r = 0; /* raio do marcador de lista */ + switch (k->kind) { + case BLK_H: + fs = font_size + (7 - k->level) * 4; + if (fs < font_size) fs = font_size; + bold = true; + y += (fs - font_size) / 2; + break; + case BLK_P: break; + case BLK_QUOTE: italic = true; indent = 14; break; + case BLK_CODE: mono = true; indent = 14; break; + case BLK_HR: break; + case BLK_LI: indent = 12; bullet_r = (fs / 5) + 1; break; + } + if (k->kind == BLK_HR) { + b_fmt(&body, " \n"); + y += line_h / 2; + continue; + } + if (bullet_r) { + b_str(&body, " \n"); + } + const char* txt = k->text ? k->text : ""; + if (k->kind == BLK_LI && k->ordered) { + snprintf(num, sizeof(num), "%d. ", k->index); + prefix = num; + } + b_str(&body, " kind == BLK_LI ? 14 : 0)); + b_str(&body, "\" y=\""); + b_fmt(&body, "%d", y); + b_str(&body, "\" font-family=\""); + b_str(&body, mono ? "monospace" : "sans-serif"); + b_str(&body, "\" font-size=\""); + b_fmt(&body, "%d", fs); + b_str(&body, "\""); + if (bold) b_str(&body, " font-weight=\"bold\""); + if (italic) b_str(&body, " font-style=\"italic\""); + b_str(&body, " fill=\"#"); + b_str(&body, k->kind == BLK_QUOTE ? "666666" : (mono ? "333333" : "111111")); + b_str(&body, "\">"); + b_esc(&body, prefix, strlen(prefix)); + /* texto simples (sem marcadores inline) */ + for (const char* p = txt; *p; p++) { + if (*p == '*' || *p == '`') continue; + b_esc(&body, p, 1); + } + b_str(&body, "\n"); + y += (fs > font_size ? line_h + (fs - font_size) : line_h); + } + int height = y + pad; + + Buf out = {0}; + b_str(&out, "\n"); + b_str(&out, " \n"); + b_str(&out, body.p ? body.p : ""); + b_str(&out, ""); + free(body.p); + doc_free(d); free(d); + return out.p; +} + +char* tb_markdown_to_svg(const char* md) { return tb_markdown_to_svg_opts(md, 640, 16); } + +/* ---------------------------------------------------------------- Blocos */ +static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; +} +static void eval_html(TinyBlocks_Block* self, TinyBlocks* rt) { + char* s = tb_markdown_to_html(in_text(self, rt, 0)); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); free(s); self->dirty = false; +} +static void eval_xml(TinyBlocks_Block* self, TinyBlocks* rt) { + char* s = tb_markdown_to_xml(in_text(self, rt, 0)); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); free(s); self->dirty = false; +} +static void eval_svg(TinyBlocks_Block* self, TinyBlocks* rt) { + char* s = tb_markdown_to_svg(in_text(self, rt, 0)); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); free(s); 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 markdown_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Markdown", + { 96/255.f, 125/255.f, 139/255.f, 1.f}, + { 55/255.f, 71/255.f, 79/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + static const TinyBlocks_SlotDesc in_md[] = {{"markdown", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc out_text[] = {{"texto", TB_VALUE_TEXT}}; + return reg(rt, lib, "Markdown.ToHtml", in_md, 1, out_text, 1, eval_html) + && reg(rt, lib, "Markdown.ToXml", in_md, 1, out_text, 1, eval_xml) + && reg(rt, lib, "Markdown.ToSvg", in_md, 1, out_text, 1, eval_svg); +} + +TINYBLOCKS_DEFINE_LIBRARY(markdown, "tinyblocks-markdown", "1.0.0", markdown_init, NULL) + +const TinyBlocks_LibraryDescriptor* tb_markdown_get_library(void) { + return &_tb_lib_desc_markdown; +} diff --git a/libraries/tinyblocks-regex/Makefile b/libraries/tinyblocks-regex/Makefile new file mode 100644 index 0000000..b9cc738 --- /dev/null +++ b/libraries/tinyblocks-regex/Makefile @@ -0,0 +1,28 @@ +# Makefile da library regex (categoria "Regex") +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +OBJ := $(BUILD)/tb_regex.o +LIB_A := $(BUILD)/libtinyblocks-regex.a +LIB_SO := $(BUILD)/libtinyblocks-regex.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_regex.c include/tb_regex.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-regex/include/tb_regex.h b/libraries/tinyblocks-regex/include/tb_regex.h new file mode 100644 index 0000000..d7cd34c --- /dev/null +++ b/libraries/tinyblocks-regex/include/tb_regex.h @@ -0,0 +1,40 @@ +/* + * TinyBlocks - tb_regex.h + * Library tinyblocks-regex: expressoes regulares (POSIX ERE) para busca, + * substituicao e divisao de texto. Independente do editor. + */ +#ifndef TINYBLOCKS_REGEX_H +#define TINYBLOCKS_REGEX_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_regex_get_library(void); + +/* -- API C --------------------------------------------------------------- */ + +/* Verdadeiro se o padrao casa em algum ponto do texto. */ +TB_API bool tb_regex_test(const char* text, const char* pattern); +/* Verdadeiro se o padrao casa o texto inteiro (ancorado). */ +TB_API bool tb_regex_match(const char* text, const char* pattern); + +/* Primeiro casamento (malloc; libere com free) ou NULL. */ +TB_API char* tb_regex_find(const char* text, const char* pattern); +/* Grupo i do primeiro casamento (0 = casamento inteiro). */ +TB_API char* tb_regex_group(const char* text, const char* pattern, int group); +/* Quantidade de grupos de captura do padrao (-1 em erro). */ +TB_API int tb_regex_group_count(const char* text, const char* pattern); +/* Numero de casamentos. */ +TB_API int tb_regex_count(const char* text, const char* pattern); + +/* Substitui todas as ocorrencias. Em `repl`, $0..$9 inserem os grupos e + * $$ insere um '$'. Devolve texto (malloc). */ +TB_API char* tb_regex_replace(const char* text, const char* pattern, const char* repl); + +/* Divide o texto pelos casamentos; devolve vetor de strings terminado por + * NULL (libere cada item e o vetor). */ +TB_API char** tb_regex_split(const char* text, const char* pattern, int* out_count); +TB_API void tb_regex_free_list(char** list); + +TB_API const char* tb_regex_last_error(void); + +#endif /* TINYBLOCKS_REGEX_H */ diff --git a/libraries/tinyblocks-regex/library.toml b/libraries/tinyblocks-regex/library.toml new file mode 100644 index 0000000..c7c04cc --- /dev/null +++ b/libraries/tinyblocks-regex/library.toml @@ -0,0 +1,15 @@ +# Metadados da library regex. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-regex" +version = "1.0.0" +category = "Regex" +description = "Expressoes regulares: busca, grupo, substituicao e divisao" +color = [69, 90, 100, 255] +dark = [38, 50, 56, 255] + +[build] +sources = ["src/tb_regex.c"] +includes = ["include"] +shared = "build/libtinyblocks-regex.so" +static = "build/libtinyblocks-regex.a" +depends = [] diff --git a/libraries/tinyblocks-regex/src/tb_regex.c b/libraries/tinyblocks-regex/src/tb_regex.c new file mode 100644 index 0000000..567f2eb --- /dev/null +++ b/libraries/tinyblocks-regex/src/tb_regex.c @@ -0,0 +1,318 @@ +/* + * TinyBlocks - tb_regex.c + * Categoria "Regex": Regex.Test / Match / Find / Group / Count / Replace / + * Split, sobre POSIX ERE (). + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include +#include +#include "tb_regex.h" + +#define MAX_GROUPS 32 + +static char s_err[200] = ""; +const char* tb_regex_last_error(void) { return s_err; } + +static bool compile(regex_t* re, const char* pattern) { + s_err[0] = 0; + if (!pattern) pattern = ""; + int rc = regcomp(re, pattern, REG_EXTENDED); + if (rc != 0) { + char msg[160]; + regerror(rc, re, msg, sizeof(msg)); + snprintf(s_err, sizeof(s_err), "%s", msg); + return false; + } + return true; +} + +bool tb_regex_test(const char* text, const char* pattern) { + regex_t re; + if (!compile(&re, pattern)) return false; + bool ok = regexec(&re, text ? text : "", 0, NULL, 0) == 0; + regfree(&re); + return ok; +} + +bool tb_regex_match(const char* text, const char* pattern) { + /* Ancora o padrao com ^( ... )$ usando grupos nao-capturantes de ERE. */ + if (!pattern) pattern = ""; + size_t n = strlen(pattern); + char* anch = (char*)malloc(n + 8); + if (!anch) return false; + anch[0] = '^'; anch[1] = '('; memcpy(anch + 2, pattern, n); + anch[n + 2] = ')'; anch[n + 3] = '$'; anch[n + 4] = 0; + bool ok = tb_regex_test(text, anch); + free(anch); + return ok; +} + +char* tb_regex_find(const char* text, const char* pattern) { + regex_t re; + if (!compile(&re, pattern)) return NULL; + regmatch_t m; + char* out = NULL; + if (regexec(&re, text ? text : "", 1, &m, 0) == 0 && m.rm_so >= 0) { + size_t len = (size_t)(m.rm_eo - m.rm_so); + out = (char*)malloc(len + 1); + if (out) { memcpy(out, text + m.rm_so, len); out[len] = 0; } + } + regfree(&re); + return out; +} + +char* tb_regex_group(const char* text, const char* pattern, int group) { + if (group < 0 || group >= MAX_GROUPS) { snprintf(s_err, sizeof(s_err), "grupo fora do intervalo"); return NULL; } + regex_t re; + if (!compile(&re, pattern)) return NULL; + regmatch_t m[MAX_GROUPS]; + char* out = NULL; + if (regexec(&re, text ? text : "", MAX_GROUPS, m, 0) == 0 && + m[group].rm_so >= 0) { + size_t len = (size_t)(m[group].rm_eo - m[group].rm_so); + out = (char*)malloc(len + 1); + if (out) { memcpy(out, text + m[group].rm_so, len); out[len] = 0; } + } + regfree(&re); + return out; +} + +int tb_regex_group_count(const char* text, const char* pattern) { + regex_t re; + if (!compile(&re, pattern)) return -1; + (void)text; + int n = (int)re.re_nsub; /* numero de subexpressoes */ + regfree(&re); + return n; +} + +int tb_regex_count(const char* text, const char* pattern) { + regex_t re; + if (!compile(&re, pattern)) return -1; + const char* p = text ? text : ""; + regmatch_t m; + int count = 0; + while (*p && regexec(&re, p, 1, &m, 0) == 0) { + count++; + if (m.rm_eo == m.rm_so) { p++; if (!*p) break; } + else p += m.rm_eo; + } + regfree(&re); + return count; +} + +/* --- Expansao do substituto -------------------------------------------- */ +typedef struct { char* p; size_t n, cap; } Buf; +static bool b_res(Buf* b, size_t extra) { + if (b->n + extra + 1 <= b->cap) return true; + size_t cap = b->cap ? b->cap : 64; + 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_put(Buf* b, const char* s, size_t n) { + if (!b_res(b, n)) return false; + memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = 0; return true; +} + +static void expand(Buf* out, const char* repl, const char* text, regmatch_t* m) { + for (const char* p = repl; *p; p++) { + if (*p == '$' && p[1] == '$') { b_put(out, "$", 1); p++; continue; } + if (*p == '$' && p[1] >= '0' && p[1] <= '9') { + int g = p[1] - '0'; + if (m[g].rm_so >= 0) b_put(out, text + m[g].rm_so, (size_t)(m[g].rm_eo - m[g].rm_so)); + p++; + continue; + } + b_put(out, p, 1); + } +} + +char* tb_regex_replace(const char* text, const char* pattern, const char* repl) { + regex_t re; + if (!compile(&re, pattern)) return NULL; + if (!text) text = ""; + if (!repl) repl = ""; + Buf out = {0}; + const char* p = text; + regmatch_t m[MAX_GROUPS]; + while (*p && regexec(&re, p, MAX_GROUPS, m, 0) == 0) { + b_put(&out, p, (size_t)m[0].rm_so); + expand(&out, repl, p, m); + if (m[0].rm_eo == m[0].rm_so) { + b_put(&out, p, 1); + p++; + if (!*p) break; + } else { + p += m[0].rm_eo; + } + } + if (*p) b_put(&out, p, strlen(p)); + regfree(&re); + if (!out.p) { out.p = (char*)malloc(1); if (out.p) out.p[0] = 0; } + return out.p; +} + +char** tb_regex_split(const char* text, const char* pattern, int* out_count) { + if (out_count) *out_count = 0; + regex_t re; + if (!compile(&re, pattern)) return NULL; + if (!text) text = ""; + size_t cap = 8, n = 0; + char** list = (char**)malloc(cap * sizeof(char*)); + if (!list) { regfree(&re); return NULL; } + const char* p = text; + regmatch_t m; + for (;;) { + if (*p && regexec(&re, p, 1, &m, 0) == 0) { + size_t len = (size_t)m.rm_so; + char* item = (char*)malloc(len + 1); + if (!item) break; + memcpy(item, p, len); item[len] = 0; + if (n + 2 > cap) { cap *= 2; list = (char**)realloc(list, cap * sizeof(char*)); } + list[n++] = item; + if (m.rm_eo == m.rm_so) { + if (!p[m.rm_so]) { p += m.rm_so; break; } + /* casa vazio: emite 1 char e continua */ + char* one = (char*)malloc(2); + one[0] = p[m.rm_so]; one[1] = 0; + list[n++] = one; + p += m.rm_so + 1; + } else { + p += m.rm_eo; + } + } else { + size_t len = strlen(p); + char* item = (char*)malloc(len + 1); + if (!item) break; + memcpy(item, p, len); item[len] = 0; + if (n + 1 > cap) { cap += 1; list = (char**)realloc(list, cap * sizeof(char*)); } + list[n++] = item; + break; + } + } + regfree(&re); + list[n] = NULL; + if (out_count) *out_count = (int)n; + return list; +} + +void tb_regex_free_list(char** list) { + if (!list) return; + for (int i = 0; list[i]; i++) free(list[i]); + free(list); +} + +/* ---------------------------------------------------------------- Blocos */ +static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; +} +static double in_real(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_REAL) return v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer; + return 0; +} + +static void eval_test(TinyBlocks_Block* self, TinyBlocks* rt) { + bool ok = tb_regex_test(in_text(self, rt, 0), in_text(self, rt, 1)); + tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); + self->dirty = false; +} +static void eval_match(TinyBlocks_Block* self, TinyBlocks* rt) { + bool ok = tb_regex_match(in_text(self, rt, 0), in_text(self, rt, 1)); + tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); + self->dirty = false; +} +static void eval_find(TinyBlocks_Block* self, TinyBlocks* rt) { + char* s = tb_regex_find(in_text(self, rt, 0), in_text(self, rt, 1)); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); + free(s); + self->dirty = false; +} +static void eval_group(TinyBlocks_Block* self, TinyBlocks* rt) { + char* s = tb_regex_group(in_text(self, rt, 0), in_text(self, rt, 1), (int)in_real(self, rt, 2)); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); + free(s); + self->dirty = false; +} +static void eval_count(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_block_set_output(self, 0, tb_value_integer(tb_regex_count(in_text(self, rt, 0), in_text(self, rt, 1)))); + self->dirty = false; +} +static void eval_groups(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_block_set_output(self, 0, tb_value_integer(tb_regex_group_count("", in_text(self, rt, 1)))); + self->dirty = false; +} +static void eval_replace(TinyBlocks_Block* self, TinyBlocks* rt) { + char* s = tb_regex_replace(in_text(self, rt, 0), in_text(self, rt, 1), in_text(self, rt, 2)); + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); + free(s); + self->dirty = false; +} +static void eval_split(TinyBlocks_Block* self, TinyBlocks* rt) { + int n = 0; + char** parts = tb_regex_split(in_text(self, rt, 0), in_text(self, rt, 1), &n); + TinyBlocks_JsonValue* arr = tb_json_array(); + if (arr) { + for (int i = 0; parts && parts[i]; i++) { + TinyBlocks_JsonValue* s = tb_json_string(parts[i]); + if (s) { tb_json_array_push(arr, s); tb_json_release(s); } + } + tb_block_set_output(self, 0, tb_value_json(arr)); + tb_json_release(arr); + } else { + tb_block_set_output(self, 0, tb_value_text("")); + } + tb_regex_free_list(parts); + 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 regex_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Regex", + { 69/255.f, 90/255.f, 100/255.f, 1.f}, + { 38/255.f, 50/255.f, 56/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + static const TinyBlocks_SlotDesc two[] = {{"texto", TB_VALUE_TEXT}, {"padrao", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc three[] = {{"texto", TB_VALUE_TEXT}, {"padrao", TB_VALUE_TEXT}, {"com", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc grp[] = {{"texto", TB_VALUE_TEXT}, {"padrao", TB_VALUE_TEXT}, {"grupo", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc pat[] = {{"padrao", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc out_text[] = {{"texto", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc out_bool[] = {{"verdadeiro", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc out_int[] = {{"numero", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc out_list[] = {{"lista", TB_VALUE_JSON}}; + + return reg(rt, lib, "Regex.Test", two, 2, out_bool, 1, eval_test) + && reg(rt, lib, "Regex.Match", two, 2, out_bool, 1, eval_match) + && reg(rt, lib, "Regex.Find", two, 2, out_text, 1, eval_find) + && reg(rt, lib, "Regex.Group", grp, 3, out_text, 1, eval_group) + && reg(rt, lib, "Regex.Count", two, 2, out_int, 1, eval_count) + && reg(rt, lib, "Regex.Groups", pat, 1, out_int, 1, eval_groups) + && reg(rt, lib, "Regex.Replace", three, 3, out_text, 1, eval_replace) + && reg(rt, lib, "Regex.Split", two, 2, out_list, 1, eval_split); +} + +TINYBLOCKS_DEFINE_LIBRARY(regex, "tinyblocks-regex", "1.0.0", regex_init, NULL) + +const TinyBlocks_LibraryDescriptor* tb_regex_get_library(void) { + return &_tb_lib_desc_regex; +} diff --git a/libraries/tinyblocks-syntax/Makefile b/libraries/tinyblocks-syntax/Makefile new file mode 100644 index 0000000..d477b5a --- /dev/null +++ b/libraries/tinyblocks-syntax/Makefile @@ -0,0 +1,28 @@ +# Makefile da library syntax (categoria "Sintaxe") +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +OBJ := $(BUILD)/tb_syntax.o +LIB_A := $(BUILD)/libtinyblocks-syntax.a +LIB_SO := $(BUILD)/libtinyblocks-syntax.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_syntax.c include/tb_syntax.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-syntax/include/tb_syntax.h b/libraries/tinyblocks-syntax/include/tb_syntax.h new file mode 100644 index 0000000..d295b0c --- /dev/null +++ b/libraries/tinyblocks-syntax/include/tb_syntax.h @@ -0,0 +1,43 @@ +/* + * TinyBlocks - tb_syntax.h + * Library tinyblocks-syntax: realce de sintaxe (syntax highlight) de um texto + * em varias linguagens, devolvendo o texto colorido em XML. + * Independente do editor. + * + * O XML gerado tem a forma: + * + * int x... + * ... + * + * Cada linha do texto vira um elemento ; os trechos viram com o tipo + * do token e a cor (#rrggbb). Texto fora de tokens vira . + */ +#ifndef TINYBLOCKS_SYNTAX_H +#define TINYBLOCKS_SYNTAX_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_syntax_get_library(void); + +/* -- API C --------------------------------------------------------------- */ + +/* Realca `text` como `lang` e devolve XML (malloc; libere com free). */ +TB_API char* tb_syntax_highlight(const char* text, const char* lang); + +/* Realca `text` como um trecho de codigo C numa unica linha (sem ), + * util para assinaturas/hover. Devolve XML (malloc). */ +TB_API char* tb_syntax_highlight_inline(const char* text, const char* lang); + +/* Numero de linguagens conhecidas e o nome normalizado da i-esima. */ +TB_API int tb_syntax_language_count(void); +TB_API const char* tb_syntax_language_name(int i); + +/* Cor (#rrggbb) associada a um tipo de token ("kw", "str", "cmt", ...). */ +TB_API const char* tb_syntax_type_color(const char* type); + +/* Normaliza um nome/extensao de linguagem ("py" -> "python"); nunca NULL. */ +TB_API const char* tb_syntax_normalize_lang(const char* lang); + +TB_API const char* tb_syntax_last_error(void); + +#endif /* TINYBLOCKS_SYNTAX_H */ diff --git a/libraries/tinyblocks-syntax/library.toml b/libraries/tinyblocks-syntax/library.toml new file mode 100644 index 0000000..0e1788e --- /dev/null +++ b/libraries/tinyblocks-syntax/library.toml @@ -0,0 +1,15 @@ +# Metadados da library syntax. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-syntax" +version = "1.0.0" +category = "Sintaxe" +description = "Realca sintaxe de codigo e devolve XML colorido" +color = [255, 152, 0, 255] +dark = [230, 119, 0, 255] + +[build] +sources = ["src/tb_syntax.c"] +includes = ["include"] +shared = "build/libtinyblocks-syntax.so" +static = "build/libtinyblocks-syntax.a" +depends = [] diff --git a/libraries/tinyblocks-syntax/src/tb_syntax.c b/libraries/tinyblocks-syntax/src/tb_syntax.c new file mode 100644 index 0000000..6a782ab --- /dev/null +++ b/libraries/tinyblocks-syntax/src/tb_syntax.c @@ -0,0 +1,499 @@ +/* + * 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 const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; +} + +static void eval_highlight(TinyBlocks_Block* self, TinyBlocks* rt) { + char* x = tb_syntax_highlight(in_text(self, rt, 0), in_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(in_text(self, rt, 0), in_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); + + 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; +} diff --git a/tests/markdown_test.c b/tests/markdown_test.c new file mode 100644 index 0000000..3f96c33 --- /dev/null +++ b/tests/markdown_test.c @@ -0,0 +1,87 @@ +/* + * markdown_test.c - testa tinyblocks-markdown (-> HTML / XML / SVG). + */ +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +static const char* MD = + "# Titulo\n" + "\n" + "Um paragrafo com **negrito** e *italico* e `codigo`.\n" + "\n" + "- item um\n" + "- item dois\n" + "\n" + "1. primeiro\n" + "2. segundo\n" + "\n" + "> uma citacao\n" + "\n" + "```c\n" + "int x = 1;\n" + "```\n" + "\n" + "[link](http://exemplo.com)\n" + "\n" + "---\n"; + +int main(void) { + char* h = tb_markdown_to_html(MD); + CHECK(h && strstr(h, "

Titulo

"), "html h1"); + CHECK(h && strstr(h, "negrito"), "html negrito"); + CHECK(h && strstr(h, "italico"), "html italico"); + CHECK(h && strstr(h, "codigo"), "html code inline"); + CHECK(h && strstr(h, "
    ") && strstr(h, "
  • item um
  • "), "html lista nao ordenada"); + CHECK(h && strstr(h, "
      ") && strstr(h, "
    1. primeiro
    2. "), "html lista ordenada"); + CHECK(h && strstr(h, "
      uma citacao
      "), "html citacao"); + CHECK(h && strstr(h, "
      ") && strstr(h, "int x = 1;"), "html bloco de codigo");
      +    CHECK(h && strstr(h, "link"), "html link");
      +    CHECK(h && strstr(h, "
      "), "html regra"); + free(h); + + char* x = tb_markdown_to_xml(MD); + CHECK(x && strstr(x, "") && strstr(x, ""), "xml raiz"); + CHECK(x && strstr(x, "Titulo"), "xml heading"); + CHECK(x && strstr(x, "") && strstr(x, "negrito"), "xml paragrafo/negrito"); + CHECK(x && strstr(x, "") && strstr(x, "item um"), "xml lista"); + CHECK(x && strstr(x, ""), "xml bloco de codigo"); + CHECK(x && strstr(x, "link"), "xml link"); + CHECK(x && strstr(x, ""), "xml regra"); + free(x); + + char* s = tb_markdown_to_svg(MD); + CHECK(s && strstr(s, "Titulo<"), "svg contem texto do titulo"); + free(s); + + char* s2 = tb_markdown_to_svg_opts("# H", 320, 12); + CHECK(s2 && strstr(s2, "width=\"320\""), "svg largura configuravel"); + free(s2); + + /* escaping */ + char* e = tb_markdown_to_html("a < b & c > d"); + CHECK(e && strstr(e, "a < b & c > d"), "html escapa &,<,>"); + free(e); + + TinyBlocks* rt; + tinyblocks_init(&rt, NULL); + TinyBlocks_LibraryBlock* lib = tb_library_register(rt, tb_markdown_get_library()); + CHECK(tb_rt_find_type(rt, "Markdown.ToHtml") && tb_rt_find_type(rt, "Markdown.ToXml") && + tb_rt_find_type(rt, "Markdown.ToSvg"), "blocos Markdown.* registrados"); + const TinyBlocks_Category* cat = lib ? tb_library_category(lib) : NULL; + CHECK(cat && !strcmp(cat->name, "Markdown"), "categoria 'Markdown'"); + tinyblocks_deinit(&rt); + + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +} diff --git a/tests/regex_test.c b/tests/regex_test.c new file mode 100644 index 0000000..2a4570a --- /dev/null +++ b/tests/regex_test.c @@ -0,0 +1,68 @@ +/* + * regex_test.c - testa tinyblocks-regex (POSIX ERE). + */ +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +int main(void) { + CHECK(tb_regex_test("abc123def", "[0-9]+"), "test encontra digitos"); + CHECK(!tb_regex_test("abcdef", "[0-9]+"), "test rejeita sem digitos"); + CHECK(tb_regex_match("aaa", "^a+$"), "match ancorado ok"); + CHECK(!tb_regex_match("aaab", "^a+$"), "match ancorado rejeita"); + + char* s = tb_regex_find("abc123def456", "[0-9]+"); + CHECK(s && !strcmp(s, "123"), "find primeiro casamento"); + free(s); + + CHECK(tb_regex_count("abc123def456", "[0-9]+") == 2, "count = 2"); + + s = tb_regex_group("user@host.com", "([a-z]+)@([a-z.]+)", 1); + CHECK(s && !strcmp(s, "user"), "group 1"); + free(s); + s = tb_regex_group("user@host.com", "([a-z]+)@([a-z.]+)", 2); + CHECK(s && !strcmp(s, "host.com"), "group 2"); + free(s); + CHECK(tb_regex_group_count("", "([a-z]+)@([a-z.]+)") == 2, "group_count = 2"); + + s = tb_regex_replace("abc123def456", "[0-9]+", "#"); + CHECK(s && !strcmp(s, "abc#def#"), "replace todas"); + free(s); + s = tb_regex_replace("2024-06-15", "([0-9]{4})-([0-9]{2})-([0-9]{2})", "$3/$2/$1"); + CHECK(s && !strcmp(s, "15/06/2024"), "replace com backrefs $1..$3"); + free(s); + s = tb_regex_replace("a.b", "\\.", "$$"); + CHECK(s && !strcmp(s, "a$b"), "replace com $$ literal"); + free(s); + + int n = 0; + char** parts = tb_regex_split("um,dois,tres", ",", &n); + CHECK(parts && n == 3 && !strcmp(parts[0], "um") && !strcmp(parts[1], "dois") && + !strcmp(parts[2], "tres"), "split por virgula"); + tb_regex_free_list(parts); + + parts = tb_regex_split("a1b22c", "[0-9]+", &n); + CHECK(parts && n == 3 && !strcmp(parts[0], "a") && !strcmp(parts[2], "c"), "split por regex"); + tb_regex_free_list(parts); + + CHECK(!tb_regex_test("x", "[") && strlen(tb_regex_last_error()) > 0, "padrao invalido -> erro"); + + TinyBlocks* rt; + tinyblocks_init(&rt, NULL); + TinyBlocks_LibraryBlock* lib = tb_library_register(rt, tb_regex_get_library()); + CHECK(tb_rt_find_type(rt, "Regex.Test") && tb_rt_find_type(rt, "Regex.Replace") && + tb_rt_find_type(rt, "Regex.Split") && tb_rt_find_type(rt, "Regex.Group"), + "blocos Regex.* registrados"); + const TinyBlocks_Category* cat = lib ? tb_library_category(lib) : NULL; + CHECK(cat && !strcmp(cat->name, "Regex"), "categoria 'Regex'"); + tinyblocks_deinit(&rt); + + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +} diff --git a/tests/syntax_test.c b/tests/syntax_test.c new file mode 100644 index 0000000..339929b --- /dev/null +++ b/tests/syntax_test.c @@ -0,0 +1,64 @@ +/* + * syntax_test.c - testa tinyblocks-syntax (realce -> XML). + */ +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +int main(void) { + char* x = tb_syntax_highlight("int x = 42; // ola\nchar* s = \"hi\";", "c"); + CHECK(x && strstr(x, ""), "XML com "); + CHECK(x && strstr(x, "type=\"type\"") && strstr(x, ">int<"), "'int' realcado como tipo"); + CHECK(x && strstr(x, "type=\"type\"") && strstr(x, ">char<"), "'char' como tipo"); + CHECK(x && strstr(x, ">42<"), "numero presente"); + CHECK(x && strstr(x, ">// ola<") && strstr(x, "type=\"cmt\""), "comentario de linha"); + CHECK(x && strstr(x, "type=\"str\"") && strstr(x, """) == NULL && strstr(x, "\"hi\""), "string literal"); + CHECK(x && strstr(x, "") && strstr(x, ""), "linhas separadas"); + free(x); + + x = tb_syntax_highlight("def f(x):\n return x # ret", "py"); + CHECK(x && strstr(x, ""), "python normalizado de 'py'"); + CHECK(x && strstr(x, ">def<") && strstr(x, "type=\"kw\""), "'def' keyword em python"); + CHECK(x && strstr(x, "type=\"cmt\""), "comentario '#' em python"); + free(x); + + x = tb_syntax_highlight("{\"a\": 1, \"b\": [true, null]}", "json"); + CHECK(x && strstr(x, "type=\"kw\"") && strstr(x, ">true<"), "json true/null"); + CHECK(x && strstr(x, "type=\"str\""), "json string"); + free(x); + + x = tb_syntax_highlight("texto", "xml"); + CHECK(x && strstr(x, "type=\"type\"") && strstr(x, ">a<"), "tag xml"); + CHECK(x && strstr(x, ">href<"), "atributo xml"); + free(x); + + x = tb_syntax_highlight_inline("static void eval_stage(TinyBlocks_Block *self, TinyBlocks *rt)", "c"); + CHECK(x && !strstr(x, "") && strstr(x, ">static<") && strstr(x, ">void<"), + "inline: sem , com keywords"); + free(x); + + CHECK(!strcmp(tb_syntax_normalize_lang("py"), "python"), "normalize py"); + CHECK(!strcmp(tb_syntax_normalize_lang("C"), "c"), "normalize C (case-insensitive)"); + CHECK(!strcmp(tb_syntax_normalize_lang(NULL), "texto"), "normalize NULL -> texto"); + CHECK(!strcmp(tb_syntax_normalize_lang("arquivo.c"), "c"), "normalize com extensao"); + CHECK(!strcmp(tb_syntax_type_color("kw"), "#c678dd"), "cor do tipo kw"); + CHECK(tb_syntax_language_count() >= 6, "pelo menos 6 linguagens"); + + TinyBlocks* rt; + tinyblocks_init(&rt, NULL); + TinyBlocks_LibraryBlock* lib = tb_library_register(rt, tb_syntax_get_library()); + CHECK(tb_rt_find_type(rt, "Syntax.Highlight") && tb_rt_find_type(rt, "Syntax.Inline") && + tb_rt_find_type(rt, "Syntax.Languages"), "blocos Syntax.* registrados"); + const TinyBlocks_Category* cat = lib ? tb_library_category(lib) : NULL; + CHECK(cat && !strcmp(cat->name, "Sintaxe"), "categoria 'Sintaxe'"); + tinyblocks_deinit(&rt); + + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +}