From 33705b290390ed659674b33b1e67f66b391413d4 Mon Sep 17 00:00:00 2001 From: mguinhos Date: Thu, 22 Oct 2026 13:10:09 -0300 Subject: [PATCH] Libraries os, string, number e vector (listas); pastas e booleanos no fs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tinyblocks-fs: itens da pasta (lista), quantidade/item N da pasta e os booleanos "é arquivo?", "é pasta?" e "existe?". - tinyblocks-os (categoria Sistema): sistema operacional, distribuição, versão do kernel, arquitetura, computador, usuário, pastas, CPUs, memória, tempo ligado e "o sistema é [ ]?". - tinyblocks-string (Texto): maiúsculas/minúsculas, trecho, letra N, posição, troca, apara, repete, inverte, divide em lista e testes; conta letras UTF-8. - tinyblocks-number (Números): reais, potência, raiz, arredondamentos, trigonometria em graus, logaritmos, pi, aleatório, limite, formatação, par/primo/inteiro. - tinyblocks-vector (Listas, blocos List.*): listas JSON imutáveis com adicionar, inserir, remover, trocar, item N, posição, fatia, ordenar, juntar, soma; campos aceitam "[1,2]" ou "a, b". O exemplo de desenho vetorial passa a se chamar tinyblocks-vector-draw. - Editor: saída única cujo nome termina em '?' vira bloco booleano (hexágono); listas JSON aparecem como texto no "escreva"; rótulos PT. - Testes: make test-os e make test-stdlib. Co-Authored-By: Claude Opus 5.5 --- Makefile | 28 +- examples/editor/main.c | 8 + examples/vector/vector.c | 2 +- .../internal/tb_editor_internal.h | 78 +++ libraries/tinyblocks-editor/src/tb_editor.c | 14 +- libraries/tinyblocks-fs/library.toml | 2 +- libraries/tinyblocks-fs/src/tb_fs.c | 136 ++++- libraries/tinyblocks-number/Makefile | 29 + .../tinyblocks-number/include/tb_number.h | 23 + libraries/tinyblocks-number/library.toml | 15 + libraries/tinyblocks-number/src/tb_number.c | 247 +++++++++ libraries/tinyblocks-os/Makefile | 29 + libraries/tinyblocks-os/include/tb_os.h | 27 + libraries/tinyblocks-os/library.toml | 15 + libraries/tinyblocks-os/src/tb_os.c | 236 ++++++++ libraries/tinyblocks-string/Makefile | 29 + .../tinyblocks-string/include/tb_string.h | 29 + libraries/tinyblocks-string/library.toml | 15 + libraries/tinyblocks-string/src/tb_string.c | 396 ++++++++++++++ libraries/tinyblocks-vector/Makefile | 29 + .../tinyblocks-vector/include/tb_vector.h | 27 + libraries/tinyblocks-vector/library.toml | 15 + libraries/tinyblocks-vector/src/tb_vector.c | 516 ++++++++++++++++++ tests/os_fs_test.c | 145 +++++ tests/stdlib_test.c | 181 ++++++ 25 files changed, 2262 insertions(+), 9 deletions(-) create mode 100644 libraries/tinyblocks-number/Makefile create mode 100644 libraries/tinyblocks-number/include/tb_number.h create mode 100644 libraries/tinyblocks-number/library.toml create mode 100644 libraries/tinyblocks-number/src/tb_number.c create mode 100644 libraries/tinyblocks-os/Makefile create mode 100644 libraries/tinyblocks-os/include/tb_os.h create mode 100644 libraries/tinyblocks-os/library.toml create mode 100644 libraries/tinyblocks-os/src/tb_os.c create mode 100644 libraries/tinyblocks-string/Makefile create mode 100644 libraries/tinyblocks-string/include/tb_string.h create mode 100644 libraries/tinyblocks-string/library.toml create mode 100644 libraries/tinyblocks-string/src/tb_string.c create mode 100644 libraries/tinyblocks-vector/Makefile create mode 100644 libraries/tinyblocks-vector/include/tb_vector.h create mode 100644 libraries/tinyblocks-vector/library.toml create mode 100644 libraries/tinyblocks-vector/src/tb_vector.c create mode 100644 tests/os_fs_test.c create mode 100644 tests/stdlib_test.c diff --git a/Makefile b/Makefile index 3eb6518..409ca06 100644 --- a/Makefile +++ b/Makefile @@ -73,7 +73,7 @@ SRCS := src/tinyblocks.c \ OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS)) -CAT_LIBS := events control operators variables appearance pen fs environ +CAT_LIBS := events control operators number string variables vector appearance pen fs os environ CAT_A := $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a) CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l)) CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include) @@ -95,9 +95,9 @@ 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-meta test-ppm test-bmp test-png test-image test-vg test-svg test-jpg \ - test-syntax test-regex test-markdown test-opentype \ + test-syntax test-os test-stdlib 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-events lib-control lib-operators lib-number lib-string lib-variables lib-vector lib-appearance lib-pen lib-fs lib-os \ 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-syntax lib-regex lib-markdown lib-opentype lib-api lib-libman \ @@ -234,7 +234,7 @@ lib-mcp: $(MAKE) -C $(MC_DIR) 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-appearance lib-pen lib-fs lib-os lib-number lib-string lib-vector 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-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" @@ -610,6 +610,26 @@ $(BUILD)/syntax_test: tests/syntax_test.c $(SYN_DIR)/src/tb_syntax.c static test-syntax: $(BUILD)/syntax_test ## Roda o teste da syntax (ASan/UBSan) ./$(BUILD)/syntax_test +$(BUILD)/os_fs_test: tests/os_fs_test.c $(FS_DIR)/src/tb_fs.c $(LIBDIR)/tinyblocks-os/src/tb_os.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(FS_DIR)/include -I$(LIBDIR)/tinyblocks-os/include \ + $(FS_DIR)/src/tb_fs.c $(LIBDIR)/tinyblocks-os/src/tb_os.c tests/os_fs_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group $(EXTRA_TEST_LIBS) + +test-os: $(BUILD)/os_fs_test ## Roda o teste de tinyblocks-os + pastas do tinyblocks-fs (ASan/UBSan) + ./$(BUILD)/os_fs_test + +STD_DIRS := $(LIBDIR)/tinyblocks-string $(LIBDIR)/tinyblocks-number $(LIBDIR)/tinyblocks-vector +STD_SRCS := $(foreach d,$(STD_DIRS),$(d)/src/$(patsubst tinyblocks-%,tb_%,$(notdir $(d))).c) + +$(BUILD)/stdlib_test: tests/stdlib_test.c $(STD_SRCS) static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) $(foreach d,$(STD_DIRS),-I$(d)/include) $(STD_SRCS) tests/stdlib_test.c \ + -o $@ -Wl,--start-group $(LIB_A) -Wl,--end-group -lm $(EXTRA_TEST_LIBS) + +test-stdlib: $(BUILD)/stdlib_test ## Roda o teste de tinyblocks-string/number/vector (ASan/UBSan) + ./$(BUILD)/stdlib_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 \ diff --git a/examples/editor/main.c b/examples/editor/main.c index 22aef69..72c68bd 100644 --- a/examples/editor/main.c +++ b/examples/editor/main.c @@ -29,6 +29,10 @@ #include #include #include +#include +#include +#include +#include #include /* Registra uma library de categoria: se existir o .so dela no disco, carrega @@ -62,10 +66,14 @@ int main(int argc, char** argv) { reg_core(rt, "tinyblocks-events", tb_events_get_library); reg_core(rt, "tinyblocks-control", tb_control_get_library); reg_core(rt, "tinyblocks-operators", tb_operators_get_library); + reg_core(rt, "tinyblocks-number", tb_number_get_library); + reg_core(rt, "tinyblocks-string", tb_string_get_library); reg_core(rt, "tinyblocks-variables", tb_variables_get_library); + reg_core(rt, "tinyblocks-vector", tb_vector_get_library); reg_core(rt, "tinyblocks-appearance", tb_appearance_get_library); reg_core(rt, "tinyblocks-pen", tb_pen_get_library); reg_core(rt, "tinyblocks-fs", tb_fs_get_library); + reg_core(rt, "tinyblocks-os", tb_os_get_library); /* Interface gráfica: o editor mede texto e cria o palco ao nascer */ tb_library_register(rt, tb_graphics_get_library()); diff --git a/examples/vector/vector.c b/examples/vector/vector.c index a80f728..f006195 100644 --- a/examples/vector/vector.c +++ b/examples/vector/vector.c @@ -204,7 +204,7 @@ static void vector_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { } TINYBLOCKS_DEFINE_LIBRARY(vector, - "tinyblocks-vector", + "tinyblocks-vector-draw", "1.0.0", vector_init, vector_deinit) diff --git a/libraries/tinyblocks-editor/internal/tb_editor_internal.h b/libraries/tinyblocks-editor/internal/tb_editor_internal.h index 04d3c58..7351864 100644 --- a/libraries/tinyblocks-editor/internal/tb_editor_internal.h +++ b/libraries/tinyblocks-editor/internal/tb_editor_internal.h @@ -302,6 +302,84 @@ static const BlockSpec s_specs[] = { {"Stage.ImageByName", "desenhe imagem nome %1 em x %2 y %3", "|0|0"}, {"Stage.ImageByNumber", "desenhe imagem número %1 em x %2 y %3", "1|0|0"}, {"Stage.Text", "escreva %1 no palco em x %2 y %3", "Olá!|-40|0"}, + /* Arquivos: pastas e testes (tinyblocks-fs) */ + {"FS.ListDir", "itens da pasta %1", ".|"}, + {"FS.ListCount", "quantidade de itens na pasta %1", ".|"}, + {"FS.ListItem", "item %2 da pasta %1", ".|1"}, + {"FS.IsFile", "%1 é arquivo?", "projeto.json"}, + {"FS.IsDir", "%1 é pasta?", "."}, + {"FS.Exists", "%1 existe?", "projeto.json"}, + /* Sistema (tinyblocks-os) */ + {"OS.Name", "sistema operacional", NULL}, + {"OS.Distro", "distribuição", NULL}, + {"OS.Version", "versão do kernel", NULL}, + {"OS.Arch", "arquitetura", NULL}, + {"OS.Hostname", "nome do computador", NULL}, + {"OS.User", "usuário", NULL}, + {"OS.Home", "pasta pessoal", NULL}, + {"OS.Cwd", "pasta atual", NULL}, + {"OS.Cpus", "número de processadores", NULL}, + {"OS.MemoryMB", "memória total (MB)", NULL}, + {"OS.UptimeS", "tempo ligado (segundos)", NULL}, + {"OS.Is", "o sistema é %1?", "Linux"}, + /* Números (tinyblocks-number) */ + {"Number.Div", "%1 ÷ %2", "10|4"}, + {"Number.Pow", "%1 elevado a %2", "2|10"}, + {"Number.Sqrt", "raiz quadrada de %1", "16"}, + {"Number.Round", "arredonde %1", "2.5"}, + {"Number.Floor", "arredonde %1 para baixo", "2.7"}, + {"Number.Ceil", "arredonde %1 para cima", "2.1"}, + {"Number.RoundTo", "arredonde %1 com %2 casas", "3.14159|2"}, + {"Number.Sin", "seno de %1", "90"}, + {"Number.Cos", "cosseno de %1", "0"}, + {"Number.Tan", "tangente de %1", "45"}, + {"Number.Asin", "arco-seno de %1", "1"}, + {"Number.Acos", "arco-cosseno de %1", "1"}, + {"Number.Atan", "arco-tangente de %1", "1"}, + {"Number.Log10", "log de %1", "100"}, + {"Number.Ln", "ln de %1", "1"}, + {"Number.Exp", "e elevado a %1", "1"}, + {"Number.Pi", "pi", NULL}, + {"Number.Random", "aleatório real entre %1 e %2", "0|1"}, + {"Number.Clamp", "limite %1 entre %2 e %3", "150|0|100"}, + {"Number.Format", "%1 com %2 casas decimais", "3.14159|2"}, + {"Number.IsEven", "%1 é par?", "4"}, + {"Number.IsPrime", "%1 é primo?", "7"}, + {"Number.IsInteger", "%1 é inteiro?", "2.5"}, + /* Texto (tinyblocks-string) */ + {"String.Upper", "maiúsculas de %1", "maçã"}, + {"String.Lower", "minúsculas de %1", "MAÇÃ"}, + {"String.Sub", "letras %2 a %3 de %1", "TinyBlocks|1|4"}, + {"String.Letter", "letra %2 de %1", "maçã|3"}, + {"String.Length", "número de letras de %1", "maçã"}, + {"String.Find", "posição de %2 em %1", "banana|na"}, + {"String.Replace", "troque %2 por %3 em %1", "olá mundo|mundo|TinyBlocks"}, + {"String.Trim", "sem espaços nas pontas %1", " olá "}, + {"String.Repeat", "repita %1 %2 vezes", "ab|3"}, + {"String.Reverse", "inverta %1", "maçã"}, + {"String.Split", "divida %1 por %2", "maçã,banana,uva|,"}, + {"String.Contains", "%1 contém %2?", "maçã|Ç"}, + {"String.StartsWith", "%1 começa com %2?", "TinyBlocks|Tiny"}, + {"String.EndsWith", "%1 termina com %2?", "foto.png|.png"}, + {"String.IsNumber", "%1 é número?", "3.14"}, + {"String.IsEmpty", "%1 está vazio?", ""}, + /* Listas (tinyblocks-vector) */ + {"List.Empty", "lista vazia", NULL}, + {"List.Of", "lista com %1 %2 %3", "maçã|banana|uva"}, + {"List.Range", "números de %1 até %2", "1|10"}, + {"List.Add", "adicione %2 ao fim de %1", "1, 2, 3|4"}, + {"List.Insert", "insira %2 na posição %3 de %1", "a, c|b|2"}, + {"List.Remove", "remova o item %2 de %1", "a, b, c|2"}, + {"List.Replace", "troque o item %2 de %1 por %3", "a, b, c|2|B"}, + {"List.Item", "item %2 de %1", "maçã, banana, uva|2"}, + {"List.Length", "tamanho da lista %1", "maçã, banana, uva"}, + {"List.IndexOf", "posição de %2 na lista %1", "maçã, banana, uva|uva"}, + {"List.Contains", "%1 contém o item %2?", "maçã, banana, uva|banana"}, + {"List.Slice", "itens %2 a %3 de %1", "1, 2, 3, 4, 5|2|4"}, + {"List.Reverse", "inverta a lista %1", "1, 2, 3"}, + {"List.Sort", "ordene %1", "3, 1, 2"}, + {"List.Join", "junte os itens de %1 com %2", "a, b, c| - "}, + {"List.Sum", "soma dos itens de %1", "1, 2, 3"}, /* Curvas (lista de pontos [x,y]) */ {"Curves.Line", "reta de x %1 y %2 até x %3 y %4 com %5 passos", "0|0|100|0|20"}, {"Curves.Bezier", "bezier de x %1 y %2 controles (%3,%4) (%5,%6) até x %7 y %8 com %9 passos", "0|0|0|80|100|80|100|0|20"}, diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index c8e899b..b9733d1 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -124,7 +124,12 @@ static void value_to_str(const TinyBlocks_Value* v, char* buf, size_t cap) { case TB_VALUE_TEXT: snprintf(buf, cap, "%s", v->as.text ? v->as.text : ""); break; case TB_VALUE_BLOCK: snprintf(buf, cap, "[bloco]"); break; case TB_VALUE_VECTOR: snprintf(buf, cap, "[vetor]"); break; - case TB_VALUE_JSON: snprintf(buf, cap, "[json]"); break; + case TB_VALUE_JSON: { + char* js = v->as.json ? tb_json_stringify(v->as.json) : NULL; + snprintf(buf, cap, "%s", js ? js : "[json]"); + free(js); + break; + } case TB_VALUE_IMAGE: snprintf(buf, cap, "[imagem %dx%d]", tb_image_width(v->as.image), tb_image_height(v->as.image)); break; default: buf[0] = 0; break; @@ -218,6 +223,13 @@ static Shape shape_of(const TinyBlocks_TypeBlock* t) { strcmp(n, "Operators.Gt") == 0 || strcmp(n, "Operators.And") == 0 || strcmp(n, "Operators.Or") == 0 || strcmp(n, "Operators.Not") == 0) return SH_BOOL; + /* Convencao para as libraries: uma unica saida cujo nome termina em '?' + (ex.: "é pasta?") e um bloco booleano. */ + if (t->output_desc_count == 1 && t->output_descs && t->output_descs[0].name) { + const char* on = t->output_descs[0].name; + size_t ol = strlen(on); + if (ol > 0 && on[ol - 1] == '?') return SH_BOOL; + } return t->output_desc_count > 0 ? SH_REPORTER : SH_STACK; } diff --git a/libraries/tinyblocks-fs/library.toml b/libraries/tinyblocks-fs/library.toml index 79dc783..b70d57c 100644 --- a/libraries/tinyblocks-fs/library.toml +++ b/libraries/tinyblocks-fs/library.toml @@ -3,7 +3,7 @@ name = "tinyblocks-fs" version = "1.0.0" category = "Arquivos" -description = "Abra, leia, escreva, anexe e posicao de arquivo" +description = "Abra, leia, escreva e anexe arquivos; liste pastas; teste arquivo/pasta" color = [0, 188, 212, 255] dark = [0, 151, 167, 255] diff --git a/libraries/tinyblocks-fs/src/tb_fs.c b/libraries/tinyblocks-fs/src/tb_fs.c index abecc5b..d4e8db1 100644 --- a/libraries/tinyblocks-fs/src/tb_fs.c +++ b/libraries/tinyblocks-fs/src/tb_fs.c @@ -1,6 +1,7 @@ /* * TinyBlocks - tb_fs.c - * Categoria "Arquivos": abra / leia / escreva / anexe / posicao. + * Categoria "Arquivos": abra / leia / escreva / anexe / posicao, listar + * pasta (FS.ListDir/ListCount/ListItem) e testes FS.IsFile/IsDir/Exists. * Mantem uma pequena tabela de arquivos abertos (handle inteiro >= 1). */ #define _POSIX_C_SOURCE 200809L @@ -8,8 +9,12 @@ #include #include #include +#include +#include +#include #include +#include #include "tb_fs.h" #define FS_MAX_FILES 64 @@ -107,6 +112,104 @@ static void eval_close(TinyBlocks_Block* self, TinyBlocks* rt) { self->dirty = false; } +/* -- Pastas --------------------------------------------------------------- */ + +static int cmp_name(const void* a, const void* b) { + return strcasecmp(*(char* const*)a, *(char* const*)b); +} + +/* Nomes da pasta (sem "." e ".."), em ordem alfabetica. Vazio = pasta + atual. Devolve um vetor alocado (libere com free_names) e o total. */ +static char** list_names(const char* path, int* count) { + *count = 0; + DIR* d = opendir(path[0] ? path : "."); + if (!d) return NULL; + char** v = NULL; + int n = 0, cap = 0; + struct dirent* de; + while ((de = readdir(d)) != NULL) { + if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; + if (n == cap) { + int nc = cap ? cap * 2 : 32; + char** nv = realloc(v, (size_t)nc * sizeof(char*)); + if (!nv) break; + v = nv; + cap = nc; + } + size_t len = strlen(de->d_name); + char* copy = malloc(len + 1); + if (!copy) break; + memcpy(copy, de->d_name, len + 1); + v[n++] = copy; + } + closedir(d); + if (n > 1) qsort(v, (size_t)n, sizeof(char*), cmp_name); + *count = n; + return v; +} + +static void free_names(char** v, int n) { + for (int i = 0; i < n; i++) free(v[i]); + free(v); +} + +static void eval_listdir(TinyBlocks_Block* self, TinyBlocks* rt) { + int n = 0; + char** names = list_names(in_text(self, rt, 0), &n); + TinyBlocks_JsonValue* arr = tb_json_array(); + for (int i = 0; arr && i < n; i++) { + TinyBlocks_JsonValue* s = tb_json_string(names[i]); + if (s) { tb_json_array_push(arr, s); tb_json_release(s); } + } + free_names(names, n); + tb_block_set_output(self, 0, tb_value_json(arr)); + tb_json_release(arr); + self->dirty = false; +} + +static void eval_listcount(TinyBlocks_Block* self, TinyBlocks* rt) { + int n = 0; + char** names = list_names(in_text(self, rt, 0), &n); + free_names(names, n); + tb_block_set_output(self, 0, tb_value_integer(n)); + self->dirty = false; +} + +/* item N (1..total) da pasta, em ordem alfabetica; fora da faixa = "" */ +static void eval_listitem(TinyBlocks_Block* self, TinyBlocks* rt) { + int n = 0; + char** names = list_names(in_text(self, rt, 0), &n); + int64_t k = in_int(self, rt, 1); + const char* item = (k >= 1 && k <= n) ? names[k - 1] : ""; + tb_block_set_output(self, 0, tb_value_text(item)); + free_names(names, n); + self->dirty = false; +} + +static void eval_isfile(TinyBlocks_Block* self, TinyBlocks* rt) { + struct stat st; + const char* p = in_text(self, rt, 0); + bool ok = p[0] && stat(p, &st) == 0 && S_ISREG(st.st_mode); + tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); + self->dirty = false; +} + +static void eval_isdir(TinyBlocks_Block* self, TinyBlocks* rt) { + struct stat st; + const char* p = in_text(self, rt, 0); + bool ok = p[0] && stat(p, &st) == 0 && S_ISDIR(st.st_mode); + tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); + self->dirty = false; +} + +static void eval_exists(TinyBlocks_Block* self, TinyBlocks* rt) { + struct stat st; + const char* p = in_text(self, rt, 0); + bool ok = p[0] && stat(p, &st) == 0; + tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); + self->dirty = false; +} + /* -- Registro ------------------------------------------------------------ */ static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, @@ -134,13 +237,42 @@ static bool fs_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static const TinyBlocks_SlotDesc handle_out[]= {{"handle", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc pos_out[] = {{"posicao",TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc dir_in[] = {{"pasta", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc item_in[] = {{"pasta", TB_VALUE_TEXT}, {"numero", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc path_in[] = {{"caminho", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}}; + static const TinyBlocks_SlotDesc count_out[] = {{"quantidade", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc name_out[] = {{"nome", TB_VALUE_TEXT}}; + /* saida terminada em '?' = bloco booleano (hexagonal no editor) */ + static const TinyBlocks_SlotDesc file_out[] = {{"é arquivo?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc isdir_out[] = {{"é pasta?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc exist_out[] = {{"existe?", TB_VALUE_INTEGER}}; + + TB_BLOCK_META("FS.ListDir", "eval_listdir", + "Lista com os nomes dos itens da pasta (ordem alfabetica)"); + TB_BLOCK_META("FS.ListCount", "eval_listcount", + "Quantos itens (arquivos e pastas) a pasta tem"); + TB_BLOCK_META("FS.ListItem", "eval_listitem", + "Nome do item N da pasta (1 = primeiro, ordem alfabetica)"); + TB_BLOCK_META("FS.IsFile", "eval_isfile", + "Verdadeiro se o caminho for um arquivo"); + TB_BLOCK_META("FS.IsDir", "eval_isdir", + "Verdadeiro se o caminho for uma pasta"); + TB_BLOCK_META("FS.Exists", "eval_exists", + "Verdadeiro se o caminho existir (arquivo ou pasta)"); return reg(rt, lib, "FS.Open", open_in, 1, handle_out, 1, eval_open) && reg(rt, lib, "FS.Read", read_in, 2, text_out, 1, eval_read) && reg(rt, lib, "FS.Write", write_in, 2, NULL, 0, eval_write) && reg(rt, lib, "FS.Append", append_in, 2, NULL, 0, eval_append) && reg(rt, lib, "FS.Tell", tell_in, 1, pos_out, 1, eval_tell) - && reg(rt, lib, "FS.Close", close_in, 1, NULL, 0, eval_close); + && reg(rt, lib, "FS.Close", close_in, 1, NULL, 0, eval_close) + && reg(rt, lib, "FS.ListDir", dir_in, 1, list_out, 1, eval_listdir) + && reg(rt, lib, "FS.ListCount", dir_in, 1, count_out, 1, eval_listcount) + && reg(rt, lib, "FS.ListItem", item_in, 2, name_out, 1, eval_listitem) + && reg(rt, lib, "FS.IsFile", path_in, 1, file_out, 1, eval_isfile) + && reg(rt, lib, "FS.IsDir", path_in, 1, isdir_out, 1, eval_isdir) + && reg(rt, lib, "FS.Exists", path_in, 1, exist_out, 1, eval_exists); } static void fs_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { diff --git a/libraries/tinyblocks-number/Makefile b/libraries/tinyblocks-number/Makefile new file mode 100644 index 0000000..69fb805 --- /dev/null +++ b/libraries/tinyblocks-number/Makefile @@ -0,0 +1,29 @@ +# Makefile da library number (categoria "Números") +# Constroi build/libtinyblocks-number.a e build/libtinyblocks-number.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -I../../include -Iinclude + +OBJ := $(BUILD)/tb_number.o +LIB_A := $(BUILD)/libtinyblocks-number.a +LIB_SO := $(BUILD)/libtinyblocks-number.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_number.c include/tb_number.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ -lm + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-number/include/tb_number.h b/libraries/tinyblocks-number/include/tb_number.h new file mode 100644 index 0000000..0bb9785 --- /dev/null +++ b/libraries/tinyblocks-number/include/tb_number.h @@ -0,0 +1,23 @@ +/* + * TinyBlocks - tb_number.h + * Library tinyblocks-number: matematica com numeros reais (divisao, + * potencia, raiz, arredondamentos, trigonometria em graus, logaritmos, pi, + * aleatorio real, limite, formatacao) e testes par/primo/inteiro. + * Registra a categoria "Números". + */ +#ifndef TINYBLOCKS_NUMBER_H +#define TINYBLOCKS_NUMBER_H + +#include +#include +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_number_get_library(void); + +/* Funcoes usadas pelos blocos (uteis tambem direto de C) */ +TB_API double tb_number_round_to(double x, int places); +TB_API bool tb_number_is_prime(long long n); +/* Formata com `places` casas, sem zeros a direita se places < 0 */ +TB_API void tb_number_format (double x, int places, char* out, size_t cap); + +#endif /* TINYBLOCKS_NUMBER_H */ diff --git a/libraries/tinyblocks-number/library.toml b/libraries/tinyblocks-number/library.toml new file mode 100644 index 0000000..b6eca6e --- /dev/null +++ b/libraries/tinyblocks-number/library.toml @@ -0,0 +1,15 @@ +# Metadados da library number. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-number" +version = "1.0.0" +category = "Números" +description = "Numeros reais - divisao, potencia, raiz, arredondar, trigonometria, primo" +color = [139, 195, 74, 255] +dark = [104, 159, 56, 255] + +[build] +sources = ["src/tb_number.c"] +includes = ["include"] +shared = "build/libtinyblocks-number.so" +static = "build/libtinyblocks-number.a" +depends = [] diff --git a/libraries/tinyblocks-number/src/tb_number.c b/libraries/tinyblocks-number/src/tb_number.c new file mode 100644 index 0000000..675f2ac --- /dev/null +++ b/libraries/tinyblocks-number/src/tb_number.c @@ -0,0 +1,247 @@ +/* + * TinyBlocks - tb_number.c + * Categoria "Números": matematica com numeros reais. Number.Div / Pow / + * Sqrt / Round / Floor / Ceil / RoundTo / Sin / Cos / Tan / Asin / Acos / + * Atan / Log10 / Ln / Exp / Pi / Random / Clamp / Format e os booleanos + * Number.IsEven / IsPrime / IsInteger. + * + * Angulos em GRAUS, como no Scratch. Resultados inteiros saem como inteiro + * ("3", nao "3.0"); trigonometria e arredondada em 10 casas (sen 180 = 0). + */ +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include + +#include +#include "tb_number.h" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#define DEG (M_PI / 180.0) + +/* -- API ------------------------------------------------------------------ */ + +TB_API double tb_number_round_to(double x, int places) { + if (places < 0) places = 0; + if (places > 12) places = 12; + double k = pow(10.0, places); + return round(x * k) / k; +} + +TB_API bool tb_number_is_prime(long long n) { + if (n < 2) return false; + if (n < 4) return true; + if (n % 2 == 0 || n % 3 == 0) return false; + for (long long i = 5; i <= n / i; i += 6) + if (n % i == 0 || n % (i + 2) == 0) return false; + return true; +} + +TB_API void tb_number_format(double x, int places, char* out, size_t cap) { + if (!out || !cap) return; + if (places >= 0) { + if (places > 12) places = 12; + snprintf(out, cap, "%.*f", places, x); + return; + } + snprintf(out, cap, "%.10f", x); /* sem zeros a direita */ + char* dot = strchr(out, '.'); + if (dot) { + char* e = out + strlen(out) - 1; + while (e > dot && *e == '0') *e-- = 0; + if (e == dot) *e = 0; + } +} + +/* -- Entradas/saidas ------------------------------------------------------ */ + +static double num(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer; + if (v.kind == TB_VALUE_REAL) return v.as.real; + if (v.kind == TB_VALUE_TEXT && v.as.text) return strtod(v.as.text, NULL); + return 0.0; +} + +/* Inteiro quando o resultado for exato (e couber), senao real */ +static void out_num(TinyBlocks_Block* self, double x) { + if (isfinite(x) && x == floor(x) && fabs(x) < 1e15) + tb_block_set_output(self, 0, tb_value_integer((int64_t)x)); + else + tb_block_set_output(self, 0, tb_value_real(isfinite(x) ? x : 0.0)); + self->dirty = false; +} + +static void out_bool(TinyBlocks_Block* self, bool b) { + tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0)); + self->dirty = false; +} + +/* trigonometria: corta o ruido de ponto flutuante (sen 180 = 0, nao 1e-16) */ +static double trig(double x) { return tb_number_round_to(x, 10); } + +/* -- Blocos --------------------------------------------------------------- */ + +#define N(i) num(self, rt, (i)) + +static void eval_div(TinyBlocks_Block* self, TinyBlocks* rt) { + double b = N(1); + out_num(self, b == 0.0 ? 0.0 : N(0) / b); +} +static void eval_pow(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, pow(N(0), N(1))); } +static void eval_sqrt(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x < 0 ? 0.0 : sqrt(x)); } +static void eval_round(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, round(N(0))); } +static void eval_floor(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, floor(N(0))); } +static void eval_ceil(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, ceil(N(0))); } +static void eval_round_to(TinyBlocks_Block* self, TinyBlocks* rt) { + out_num(self, tb_number_round_to(N(0), (int)N(1))); +} +static void eval_sin(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(sin(N(0) * DEG))); } +static void eval_cos(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(cos(N(0) * DEG))); } +static void eval_tan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(tan(N(0) * DEG))); } +static void eval_asin(TinyBlocks_Block* self, TinyBlocks* rt) { + double x = N(0); + out_num(self, (x < -1 || x > 1) ? 0.0 : trig(asin(x) / DEG)); +} +static void eval_acos(TinyBlocks_Block* self, TinyBlocks* rt) { + double x = N(0); + out_num(self, (x < -1 || x > 1) ? 0.0 : trig(acos(x) / DEG)); +} +static void eval_atan(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, trig(atan(N(0)) / DEG)); } +static void eval_log10(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log10(x) : 0.0); } +static void eval_ln(TinyBlocks_Block* self, TinyBlocks* rt) { double x = N(0); out_num(self, x > 0 ? log(x) : 0.0); } +static void eval_exp(TinyBlocks_Block* self, TinyBlocks* rt) { out_num(self, exp(N(0))); } +static void eval_pi(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_num(self, M_PI); } + +static void eval_random(TinyBlocks_Block* self, TinyBlocks* rt) { + double a = N(0), b = N(1); + if (a > b) { double t = a; a = b; b = t; } + double r = a + (b - a) * ((double)rand() / ((double)RAND_MAX + 1.0)); + tb_block_set_output(self, 0, tb_value_real(r)); /* sempre real */ + self->dirty = false; +} + +static void eval_clamp(TinyBlocks_Block* self, TinyBlocks* rt) { + double x = N(0), lo = N(1), hi = N(2); + if (lo > hi) { double t = lo; lo = hi; hi = t; } + out_num(self, x < lo ? lo : x > hi ? hi : x); +} + +static void eval_format(TinyBlocks_Block* self, TinyBlocks* rt) { + char buf[64]; + tb_number_format(N(0), (int)N(1), buf, sizeof(buf)); + tb_block_set_output(self, 0, tb_value_text(buf)); + self->dirty = false; +} + +static void eval_is_even(TinyBlocks_Block* self, TinyBlocks* rt) { + double x = N(0); + out_bool(self, x == floor(x) && fmod(fabs(x), 2.0) == 0.0); +} +static void eval_is_prime(TinyBlocks_Block* self, TinyBlocks* rt) { + double x = N(0); + out_bool(self, x == floor(x) && x < 9e15 && tb_number_is_prime((long long)x)); +} +static void eval_is_int(TinyBlocks_Block* self, TinyBlocks* rt) { + double x = N(0); + out_bool(self, isfinite(x) && x == floor(x)); +} + +/* -- Registro ------------------------------------------------------------- */ + +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 number_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + srand((unsigned)time(NULL) ^ 0x5bd1e995u); + static const TinyBlocks_Category cat = { + "Números", + {139/255.f, 195/255.f, 74/255.f, 1.f}, + {104/255.f, 159/255.f, 56/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + TB_BLOCK_META("Number.Div", "eval_div", "Divisao com casas decimais (por 0 da 0)"); + TB_BLOCK_META("Number.Pow", "eval_pow", "A elevado a B"); + TB_BLOCK_META("Number.Sqrt", "eval_sqrt", "Raiz quadrada"); + TB_BLOCK_META("Number.Round", "eval_round", "Arredonda para o inteiro mais proximo"); + TB_BLOCK_META("Number.Floor", "eval_floor", "Arredonda para baixo"); + TB_BLOCK_META("Number.Ceil", "eval_ceil", "Arredonda para cima"); + TB_BLOCK_META("Number.RoundTo", "tb_number_round_to", "Arredonda mantendo N casas decimais"); + TB_BLOCK_META("Number.Sin", "eval_sin", "Seno (angulo em graus)"); + TB_BLOCK_META("Number.Cos", "eval_cos", "Cosseno (angulo em graus)"); + TB_BLOCK_META("Number.Tan", "eval_tan", "Tangente (angulo em graus)"); + TB_BLOCK_META("Number.Asin", "eval_asin", "Arco-seno, em graus"); + TB_BLOCK_META("Number.Acos", "eval_acos", "Arco-cosseno, em graus"); + TB_BLOCK_META("Number.Atan", "eval_atan", "Arco-tangente, em graus"); + TB_BLOCK_META("Number.Log10", "eval_log10", "Logaritmo na base 10"); + TB_BLOCK_META("Number.Ln", "eval_ln", "Logaritmo natural (base e)"); + TB_BLOCK_META("Number.Exp", "eval_exp", "e elevado a X"); + TB_BLOCK_META("Number.Pi", "eval_pi", "O numero pi (3,14159...)"); + TB_BLOCK_META("Number.Random", "eval_random", "Numero real aleatorio entre A e B"); + TB_BLOCK_META("Number.Clamp", "eval_clamp", "Prende o numero entre o minimo e o maximo"); + TB_BLOCK_META("Number.Format", "tb_number_format", "Texto do numero com N casas decimais"); + TB_BLOCK_META("Number.IsEven", "eval_is_even", "Verdadeiro se o numero for par"); + TB_BLOCK_META("Number.IsPrime", "tb_number_is_prime", "Verdadeiro se o numero for primo"); + TB_BLOCK_META("Number.IsInteger", "eval_is_int", "Verdadeiro se o numero nao tiver casas decimais"); + + static const TinyBlocks_SlotDesc n1[] = {{"x", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc n2[] = {{"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc n3[] = {{"x", TB_VALUE_REAL}, {"min", TB_VALUE_REAL}, {"max", TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc nk[] = {{"x", TB_VALUE_REAL}, {"casas", TB_VALUE_INTEGER}}; + /* saida "qualquer": inteiro quando exato, senao real */ + static const TinyBlocks_SlotDesc out[] = {{"numero", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; + /* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */ + static const TinyBlocks_SlotDesc even_out[] = {{"é par?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc prime_out[] = {{"é primo?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc int_out[] = {{"é inteiro?", TB_VALUE_INTEGER}}; + + return reg(rt, lib, "Number.Div", n2, 2, out, 1, eval_div) + && reg(rt, lib, "Number.Pow", n2, 2, out, 1, eval_pow) + && reg(rt, lib, "Number.Sqrt", n1, 1, out, 1, eval_sqrt) + && reg(rt, lib, "Number.Round", n1, 1, out, 1, eval_round) + && reg(rt, lib, "Number.Floor", n1, 1, out, 1, eval_floor) + && reg(rt, lib, "Number.Ceil", n1, 1, out, 1, eval_ceil) + && reg(rt, lib, "Number.RoundTo", nk, 2, out, 1, eval_round_to) + && reg(rt, lib, "Number.Sin", n1, 1, out, 1, eval_sin) + && reg(rt, lib, "Number.Cos", n1, 1, out, 1, eval_cos) + && reg(rt, lib, "Number.Tan", n1, 1, out, 1, eval_tan) + && reg(rt, lib, "Number.Asin", n1, 1, out, 1, eval_asin) + && reg(rt, lib, "Number.Acos", n1, 1, out, 1, eval_acos) + && reg(rt, lib, "Number.Atan", n1, 1, out, 1, eval_atan) + && reg(rt, lib, "Number.Log10", n1, 1, out, 1, eval_log10) + && reg(rt, lib, "Number.Ln", n1, 1, out, 1, eval_ln) + && reg(rt, lib, "Number.Exp", n1, 1, out, 1, eval_exp) + && reg(rt, lib, "Number.Pi", NULL, 0, out, 1, eval_pi) + && reg(rt, lib, "Number.Random", n2, 2, out, 1, eval_random) + && reg(rt, lib, "Number.Clamp", n3, 3, out, 1, eval_clamp) + && reg(rt, lib, "Number.Format", nk, 2, text_out, 1, eval_format) + && reg(rt, lib, "Number.IsEven", n1, 1, even_out, 1, eval_is_even) + && reg(rt, lib, "Number.IsPrime", n1, 1, prime_out, 1, eval_is_prime) + && reg(rt, lib, "Number.IsInteger", n1, 1, int_out, 1, eval_is_int); +} + +static void number_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(number, + "tinyblocks-number", + "1.0.0", + number_init, + number_deinit) + +const TinyBlocks_LibraryDescriptor* tb_number_get_library(void) { + return &_tb_lib_desc_number; +} diff --git a/libraries/tinyblocks-os/Makefile b/libraries/tinyblocks-os/Makefile new file mode 100644 index 0000000..6f3f35e --- /dev/null +++ b/libraries/tinyblocks-os/Makefile @@ -0,0 +1,29 @@ +# Makefile da library os (categoria "Sistema") +# Constroi build/libtinyblocks-os.a e build/libtinyblocks-os.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -I../../include -Iinclude + +OBJ := $(BUILD)/tb_os.o +LIB_A := $(BUILD)/libtinyblocks-os.a +LIB_SO := $(BUILD)/libtinyblocks-os.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_os.c include/tb_os.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-os/include/tb_os.h b/libraries/tinyblocks-os/include/tb_os.h new file mode 100644 index 0000000..3216fc0 --- /dev/null +++ b/libraries/tinyblocks-os/include/tb_os.h @@ -0,0 +1,27 @@ +/* + * TinyBlocks - tb_os.h + * Library tinyblocks-os: blocos que informam sobre o sistema (nome do SO, + * distribuicao, versao do kernel, arquitetura, computador, usuario, CPUs, + * memoria, tempo ligado). Registra a categoria "Sistema". + */ +#ifndef TINYBLOCKS_OS_H +#define TINYBLOCKS_OS_H + +#include +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_os_get_library(void); + +/* Funcoes usadas pelos blocos (uteis tambem direto de C). + As de texto escrevem em out (sempre terminado em 0). */ +TB_API void tb_os_name (char* out, size_t cap); /* "Linux", "Windows", "macOS" */ +TB_API void tb_os_distro (char* out, size_t cap); /* "Ubuntu 26.04 LTS" */ +TB_API void tb_os_version (char* out, size_t cap); /* versao do kernel */ +TB_API void tb_os_arch (char* out, size_t cap); /* "x86_64", "aarch64" */ +TB_API void tb_os_hostname(char* out, size_t cap); +TB_API void tb_os_user (char* out, size_t cap); +TB_API int tb_os_cpus (void); +TB_API long long tb_os_memory_mb(void); +TB_API long long tb_os_uptime_s(void); + +#endif /* TINYBLOCKS_OS_H */ diff --git a/libraries/tinyblocks-os/library.toml b/libraries/tinyblocks-os/library.toml new file mode 100644 index 0000000..82279e9 --- /dev/null +++ b/libraries/tinyblocks-os/library.toml @@ -0,0 +1,15 @@ +# Metadados da library os. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-os" +version = "1.0.0" +category = "Sistema" +description = "Sistema operacional, versao, arquitetura, computador, usuario e recursos" +color = [92, 107, 192, 255] +dark = [57, 73, 171, 255] + +[build] +sources = ["src/tb_os.c"] +includes = ["include"] +shared = "build/libtinyblocks-os.so" +static = "build/libtinyblocks-os.a" +depends = [] diff --git a/libraries/tinyblocks-os/src/tb_os.c b/libraries/tinyblocks-os/src/tb_os.c new file mode 100644 index 0000000..1659277 --- /dev/null +++ b/libraries/tinyblocks-os/src/tb_os.c @@ -0,0 +1,236 @@ +/* + * TinyBlocks - tb_os.c + * Categoria "Sistema": OS.Name / Distro / Version / Arch / Hostname / User / + * Home / Cwd / Cpus / MemoryMB / UptimeS e o booleano OS.Is ("o sistema e + * Linux?"). Le uname(), /etc/os-release, sysconf() e /proc/uptime. + */ +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "tb_os.h" + +static void copy(char* out, size_t cap, const char* s) { + if (!out || !cap) return; + snprintf(out, cap, "%s", s ? s : ""); +} + +/* -- Consultas ------------------------------------------------------------ */ + +TB_API void tb_os_name(char* out, size_t cap) { +#if defined(__APPLE__) + copy(out, cap, "macOS"); +#elif defined(_WIN32) + copy(out, cap, "Windows"); +#else + struct utsname u; + copy(out, cap, uname(&u) == 0 ? u.sysname : "desconhecido"); +#endif +} + +/* PRETTY_NAME do /etc/os-release (ex: "Ubuntu 26.04 LTS"); sem o arquivo, + cai no nome do sistema. */ +TB_API void tb_os_distro(char* out, size_t cap) { + const char* files[2] = { "/etc/os-release", "/usr/lib/os-release" }; + for (int f = 0; f < 2; f++) { + FILE* fp = fopen(files[f], "r"); + if (!fp) continue; + char line[512]; + while (fgets(line, sizeof(line), fp)) { + if (strncmp(line, "PRETTY_NAME=", 12) != 0) continue; + char* v = line + 12; + v[strcspn(v, "\r\n")] = 0; + size_t n = strlen(v); + if (n >= 2 && (v[0] == '"' || v[0] == '\'') && v[n - 1] == v[0]) { + v[n - 1] = 0; + v++; + } + copy(out, cap, v); + fclose(fp); + return; + } + fclose(fp); + } + tb_os_name(out, cap); +} + +TB_API void tb_os_version(char* out, size_t cap) { + struct utsname u; + copy(out, cap, uname(&u) == 0 ? u.release : ""); +} + +TB_API void tb_os_arch(char* out, size_t cap) { + struct utsname u; + copy(out, cap, uname(&u) == 0 ? u.machine : ""); +} + +TB_API void tb_os_hostname(char* out, size_t cap) { + char h[256]; + if (gethostname(h, sizeof(h)) == 0) { h[sizeof(h) - 1] = 0; copy(out, cap, h); } + else copy(out, cap, ""); +} + +TB_API void tb_os_user(char* out, size_t cap) { + struct passwd* pw = getpwuid(getuid()); + if (pw && pw->pw_name) { copy(out, cap, pw->pw_name); return; } + copy(out, cap, getenv("USER")); +} + +TB_API int tb_os_cpus(void) { + long n = sysconf(_SC_NPROCESSORS_ONLN); + return n > 0 ? (int)n : 1; +} + +TB_API long long tb_os_memory_mb(void) { + long pages = sysconf(_SC_PHYS_PAGES); + long psize = sysconf(_SC_PAGESIZE); + if (pages <= 0 || psize <= 0) return 0; + return (long long)pages * (long long)psize / (1024LL * 1024LL); +} + +TB_API long long tb_os_uptime_s(void) { + FILE* fp = fopen("/proc/uptime", "r"); + if (!fp) return 0; + double up = 0; + if (fscanf(fp, "%lf", &up) != 1) up = 0; + fclose(fp); + return (long long)up; +} + +/* -- Blocos --------------------------------------------------------------- */ + +static void out_text(TinyBlocks_Block* self, void (*fn)(char*, size_t)) { + char buf[512]; + fn(buf, sizeof(buf)); + tb_block_set_output(self, 0, tb_value_text(buf)); + self->dirty = false; +} + +static void eval_name(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_name); } +static void eval_distro(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_distro); } +static void eval_version(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_version); } +static void eval_arch(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_arch); } +static void eval_hostname(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_hostname); } +static void eval_user(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; out_text(self, tb_os_user); } + +static void eval_home(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + const char* h = getenv("HOME"); + if (!h || !h[0]) { + struct passwd* pw = getpwuid(getuid()); + h = pw ? pw->pw_dir : ""; + } + tb_block_set_output(self, 0, tb_value_text(h ? h : "")); + self->dirty = false; +} + +static void eval_cwd(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + char buf[1024]; + tb_block_set_output(self, 0, tb_value_text(getcwd(buf, sizeof(buf)) ? buf : "")); + self->dirty = false; +} + +static void eval_cpus(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + tb_block_set_output(self, 0, tb_value_integer(tb_os_cpus())); + self->dirty = false; +} + +static void eval_memory(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + tb_block_set_output(self, 0, tb_value_integer(tb_os_memory_mb())); + self->dirty = false; +} + +static void eval_uptime(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + tb_block_set_output(self, 0, tb_value_integer(tb_os_uptime_s())); + self->dirty = false; +} + +/* "o sistema e [Linux]?" - compara com o nome do SO e com a distribuicao + (aceita "Linux", "macOS", "Ubuntu", ...), sem diferenciar maiusculas. */ +static void eval_is(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Value v = tb_block_get_input(self, rt, 0); + const char* want = (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; + char name[128], distro[256]; + tb_os_name(name, sizeof(name)); + tb_os_distro(distro, sizeof(distro)); + size_t wl = strlen(want); + bool ok = wl > 0 && (strcasecmp(name, want) == 0 || strncasecmp(distro, want, wl) == 0); + tb_block_set_output(self, 0, tb_value_integer(ok ? 1 : 0)); + self->dirty = false; +} + +/* -- Registro ------------------------------------------------------------- */ + +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 os_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Sistema", + { 92/255.f, 107/255.f, 192/255.f, 1.f}, + { 57/255.f, 73/255.f, 171/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + TB_BLOCK_META("OS.Name", "tb_os_name", "Nome do sistema operacional (Linux, macOS, ...)"); + TB_BLOCK_META("OS.Distro", "tb_os_distro", "Distribuicao/versao do sistema (os-release)"); + TB_BLOCK_META("OS.Version", "tb_os_version", "Versao do kernel"); + TB_BLOCK_META("OS.Arch", "tb_os_arch", "Arquitetura do processador (x86_64, aarch64, ...)"); + TB_BLOCK_META("OS.Hostname", "tb_os_hostname", "Nome do computador na rede"); + TB_BLOCK_META("OS.User", "tb_os_user", "Usuario que esta rodando o programa"); + TB_BLOCK_META("OS.Home", "eval_home", "Pasta pessoal do usuario"); + TB_BLOCK_META("OS.Cwd", "eval_cwd", "Pasta de trabalho atual"); + TB_BLOCK_META("OS.Cpus", "tb_os_cpus", "Quantos processadores (nucleos) estao ativos"); + TB_BLOCK_META("OS.MemoryMB", "tb_os_memory_mb", "Memoria RAM total, em MB"); + TB_BLOCK_META("OS.UptimeS", "tb_os_uptime_s", "Ha quantos segundos o computador esta ligado"); + TB_BLOCK_META("OS.Is", "eval_is", "Verdadeiro se o sistema (ou a distribuicao) tiver esse nome"); + + static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc num_out[] = {{"numero", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc is_in[] = {{"nome", TB_VALUE_TEXT}}; + /* saida terminada em '?' = bloco booleano (hexagonal no editor) */ + static const TinyBlocks_SlotDesc is_out[] = {{"é?", TB_VALUE_INTEGER}}; + + return reg(rt, lib, "OS.Name", NULL, 0, text_out, 1, eval_name) + && reg(rt, lib, "OS.Distro", NULL, 0, text_out, 1, eval_distro) + && reg(rt, lib, "OS.Version", NULL, 0, text_out, 1, eval_version) + && reg(rt, lib, "OS.Arch", NULL, 0, text_out, 1, eval_arch) + && reg(rt, lib, "OS.Hostname", NULL, 0, text_out, 1, eval_hostname) + && reg(rt, lib, "OS.User", NULL, 0, text_out, 1, eval_user) + && reg(rt, lib, "OS.Home", NULL, 0, text_out, 1, eval_home) + && reg(rt, lib, "OS.Cwd", NULL, 0, text_out, 1, eval_cwd) + && reg(rt, lib, "OS.Cpus", NULL, 0, num_out, 1, eval_cpus) + && reg(rt, lib, "OS.MemoryMB", NULL, 0, num_out, 1, eval_memory) + && reg(rt, lib, "OS.UptimeS", NULL, 0, num_out, 1, eval_uptime) + && reg(rt, lib, "OS.Is", is_in, 1, is_out, 1, eval_is); +} + +static void os_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(os, + "tinyblocks-os", + "1.0.0", + os_init, + os_deinit) + +const TinyBlocks_LibraryDescriptor* tb_os_get_library(void) { + return &_tb_lib_desc_os; +} diff --git a/libraries/tinyblocks-string/Makefile b/libraries/tinyblocks-string/Makefile new file mode 100644 index 0000000..72d4160 --- /dev/null +++ b/libraries/tinyblocks-string/Makefile @@ -0,0 +1,29 @@ +# Makefile da library string (categoria "Texto") +# Constroi build/libtinyblocks-string.a e build/libtinyblocks-string.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -I../../include -Iinclude + +OBJ := $(BUILD)/tb_string.o +LIB_A := $(BUILD)/libtinyblocks-string.a +LIB_SO := $(BUILD)/libtinyblocks-string.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_string.c include/tb_string.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-string/include/tb_string.h b/libraries/tinyblocks-string/include/tb_string.h new file mode 100644 index 0000000..6a6fe35 --- /dev/null +++ b/libraries/tinyblocks-string/include/tb_string.h @@ -0,0 +1,29 @@ +/* + * TinyBlocks - tb_string.h + * Library tinyblocks-string: blocos de texto (maiusculas/minusculas, trecho, + * letra N, contem/comeca/termina, posicao, troca, apara, repete, inverte, + * divide em lista, testes de numero/vazio). Ciente de UTF-8: posicoes e + * tamanhos contam letras, nao bytes. Registra a categoria "Texto". + */ +#ifndef TINYBLOCKS_STRING_H +#define TINYBLOCKS_STRING_H + +#include +#include +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_string_get_library(void); + +/* Funcoes usadas pelos blocos (uteis tambem direto de C). As que devolvem + char* alocam com malloc (libere com free). Posicoes comecam em 1. */ +TB_API size_t tb_string_length (const char* s); /* em letras */ +TB_API char* tb_string_upper (const char* s); +TB_API char* tb_string_lower (const char* s); +TB_API char* tb_string_sub (const char* s, long long from, long long to); +TB_API long long tb_string_find(const char* s, const char* what); /* 0 = nao achou */ +TB_API char* tb_string_replace(const char* s, const char* what, const char* with); +TB_API char* tb_string_trim (const char* s); +TB_API char* tb_string_reverse(const char* s); +TB_API bool tb_string_is_number(const char* s); + +#endif /* TINYBLOCKS_STRING_H */ diff --git a/libraries/tinyblocks-string/library.toml b/libraries/tinyblocks-string/library.toml new file mode 100644 index 0000000..e05ac38 --- /dev/null +++ b/libraries/tinyblocks-string/library.toml @@ -0,0 +1,15 @@ +# Metadados da library string. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-string" +version = "1.0.0" +category = "Texto" +description = "Texto - maiusculas, trecho, letra N, contem, troca, divide em lista" +color = [207, 99, 207, 255] +dark = [170, 68, 170, 255] + +[build] +sources = ["src/tb_string.c"] +includes = ["include"] +shared = "build/libtinyblocks-string.so" +static = "build/libtinyblocks-string.a" +depends = [] diff --git a/libraries/tinyblocks-string/src/tb_string.c b/libraries/tinyblocks-string/src/tb_string.c new file mode 100644 index 0000000..9c2752e --- /dev/null +++ b/libraries/tinyblocks-string/src/tb_string.c @@ -0,0 +1,396 @@ +/* + * TinyBlocks - tb_string.c + * Categoria "Texto": String.Upper / Lower / Sub / Letter / Length / Find / + * Replace / Trim / Repeat / Reverse / Split e os booleanos String.Contains / + * StartsWith / EndsWith / IsNumber / IsEmpty. + * + * Tudo conta LETRAS (pontos de codigo UTF-8), nao bytes: "maçã" tem 4. + * Maiusculas/minusculas cobrem ASCII e Latin-1 (á, ç, õ, ...), o que basta + * para portugues. "contém" ignora maiusculas, como no Scratch. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include +#include +#include "tb_string.h" + +#define STR_MAX_OUT (1u << 20) /* teto de 1 MB para "repita" */ + +/* -- UTF-8 ---------------------------------------------------------------- */ + +static size_t u8_len(unsigned char c) { + if (c < 0x80) return 1; + if ((c & 0xE0) == 0xC0) return 2; + if ((c & 0xF0) == 0xE0) return 3; + if ((c & 0xF8) == 0xF0) return 4; + return 1; /* byte invalido: conta 1 */ +} + +/* Byte onde comeca a letra `idx` (0-based); strlen se passar do fim */ +static size_t u8_offset(const char* s, size_t idx) { + size_t o = 0, n = strlen(s); + while (idx > 0 && o < n) { + size_t l = u8_len((unsigned char)s[o]); + o = o + l > n ? n : o + l; + idx--; + } + return o; +} + +static char* dup_n(const char* s, size_t n) { + char* r = malloc(n + 1); + if (!r) return NULL; + memcpy(r, s, n); + r[n] = 0; + return r; +} + +/* Muda a caixa: up = maiusculas. ASCII + Latin-1 (C3 80..9E <-> C3 A0..BE) */ +static char* change_case(const char* s, bool up) { + size_t n = strlen(s); + char* r = dup_n(s, n); + if (!r) return NULL; + for (size_t i = 0; i < n; i++) { + unsigned char c = (unsigned char)r[i]; + if (c < 0x80) { + r[i] = (char)(up ? toupper(c) : tolower(c)); + } else if (c == 0xC3 && i + 1 < n) { + unsigned char d = (unsigned char)r[i + 1]; + if (up && d >= 0xA0 && d <= 0xBE && d != 0xB7) r[i + 1] = (char)(d - 0x20); + else if (!up && d >= 0x80 && d <= 0x9E && d != 0x97) r[i + 1] = (char)(d + 0x20); + i++; + } + } + return r; +} + +/* Quantas letras ha nos primeiros `nbytes` bytes */ +static size_t u8_count(const char* s, size_t nbytes) { + size_t n = 0, o = 0; + while (o < nbytes && s[o]) { o += u8_len((unsigned char)s[o]); n++; } + return n; +} + +/* -- API ------------------------------------------------------------------ */ + +TB_API size_t tb_string_length(const char* s) { + return u8_count(s, strlen(s)); +} + +TB_API char* tb_string_upper(const char* s) { return change_case(s, true); } +TB_API char* tb_string_lower(const char* s) { return change_case(s, false); } + +/* Letras `from` ate `to` (1-based, inclusivo), cortadas aos limites */ +TB_API char* tb_string_sub(const char* s, long long from, long long to) { + long long n = (long long)tb_string_length(s); + if (from < 1) from = 1; + if (to > n) to = n; + if (from > to) return dup_n("", 0); + size_t a = u8_offset(s, (size_t)(from - 1)); + size_t b = u8_offset(s, (size_t)to); + return dup_n(s + a, b - a); +} + +TB_API long long tb_string_find(const char* s, const char* what) { + if (!what[0]) return 0; + const char* p = strstr(s, what); + if (!p) return 0; + return (long long)u8_count(s, (size_t)(p - s)) + 1; +} + +TB_API char* tb_string_replace(const char* s, const char* what, const char* with) { + size_t wl = strlen(what), rl = strlen(with), n = strlen(s); + if (!wl) return dup_n(s, n); + size_t count = 0; + for (const char* p = strstr(s, what); p; p = strstr(p + wl, what)) count++; + size_t out = n + count * rl - count * wl; + char* r = malloc(out + 1); + if (!r) return NULL; + char* o = r; + const char* cur = s; + for (const char* p = strstr(s, what); p; p = strstr(cur, what)) { + memcpy(o, cur, (size_t)(p - cur)); o += p - cur; + memcpy(o, with, rl); o += rl; + cur = p + wl; + } + strcpy(o, cur); + return r; +} + +TB_API char* tb_string_trim(const char* s) { + const char* a = s; + while (*a && isspace((unsigned char)*a)) a++; + const char* b = a + strlen(a); + while (b > a && isspace((unsigned char)b[-1])) b--; + return dup_n(a, (size_t)(b - a)); +} + +TB_API char* tb_string_reverse(const char* s) { + size_t n = strlen(s); + char* r = malloc(n + 1); + if (!r) return NULL; + size_t o = 0; + while (o < n) { + size_t l = u8_len((unsigned char)s[o]); + if (o + l > n) l = n - o; + memcpy(r + (n - o - l), s + o, l); /* letra inteira, de tras pra frente */ + o += l; + } + r[n] = 0; + return r; +} + +TB_API bool tb_string_is_number(const char* s) { + while (isspace((unsigned char)*s)) s++; + if (!*s) return false; + char* e; + strtod(s, &e); + if (e == s) return false; + while (isspace((unsigned char)*e)) e++; + return *e == 0; +} + +/* -- Entradas ------------------------------------------------------------- */ + +/* Texto da entrada i (numeros viram texto). Fica valido ate o proximo uso. */ +static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, char* buf, size_t cap) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + switch (v.kind) { + case TB_VALUE_TEXT: return v.as.text ? v.as.text : ""; + case TB_VALUE_INTEGER: snprintf(buf, cap, "%lld", (long long)v.as.integer); return buf; + case TB_VALUE_REAL: snprintf(buf, cap, "%g", v.as.real); return buf; + default: return ""; + } +} + +static long long in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_INTEGER) return v.as.integer; + if (v.kind == TB_VALUE_REAL) return (long long)v.as.real; + if (v.kind == TB_VALUE_TEXT && v.as.text) return strtoll(v.as.text, NULL, 10); + return 0; +} + +static void out_owned(TinyBlocks_Block* self, char* s) { + tb_block_set_output(self, 0, tb_value_text(s ? s : "")); + free(s); + self->dirty = false; +} + +static void out_bool(TinyBlocks_Block* self, bool b) { + tb_block_set_output(self, 0, tb_value_integer(b ? 1 : 0)); + self->dirty = false; +} + +#define TXT(i) in_text(self, rt, (i), b##i, sizeof(b##i)) + +/* -- Blocos --------------------------------------------------------------- */ + +static void eval_upper(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_upper(TXT(0))); } +static void eval_lower(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_lower(TXT(0))); } +static void eval_trim(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_trim(TXT(0))); } +static void eval_reverse(TinyBlocks_Block* self, TinyBlocks* rt) { char b0[64]; out_owned(self, tb_string_reverse(TXT(0))); } + +static void eval_sub(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + out_owned(self, tb_string_sub(TXT(0), in_int(self, rt, 1), in_int(self, rt, 2))); +} + +static void eval_letter(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + long long k = in_int(self, rt, 1); + out_owned(self, tb_string_sub(TXT(0), k, k)); +} + +static void eval_length(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + tb_block_set_output(self, 0, tb_value_integer((int64_t)tb_string_length(TXT(0)))); + self->dirty = false; +} + +static void eval_find(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64], b1[64]; + tb_block_set_output(self, 0, tb_value_integer(tb_string_find(TXT(0), TXT(1)))); + self->dirty = false; +} + +static void eval_replace(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64], b1[64], b2[64]; + out_owned(self, tb_string_replace(TXT(0), TXT(1), TXT(2))); +} + +static void eval_repeat(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + const char* s = TXT(0); + long long k = in_int(self, rt, 1); + size_t n = strlen(s); + if (k < 0) k = 0; + if (n && (size_t)k > STR_MAX_OUT / n) k = (long long)(STR_MAX_OUT / n); + char* r = malloc(n * (size_t)k + 1); + if (r) { + for (long long i = 0; i < k; i++) memcpy(r + (size_t)i * n, s, n); + r[n * (size_t)k] = 0; + } + out_owned(self, r); +} + +static void push_piece(TinyBlocks_JsonValue* arr, const char* s, size_t n) { + char* piece = dup_n(s, n); + TinyBlocks_JsonValue* item = piece ? tb_json_string(piece) : NULL; + free(piece); + if (item) { tb_json_array_push(arr, item); tb_json_release(item); } +} + +/* Divide em lista JSON; separador vazio = uma letra por item. + "a,,b" -> ["a","","b"]; "a," -> ["a",""]; "" -> [] */ +static void eval_split(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64], b1[64]; + const char* s = TXT(0); + const char* sep = TXT(1); + size_t sl = strlen(sep), n = strlen(s); + TinyBlocks_JsonValue* arr = tb_json_array(); + if (arr && n) { + if (!sl) { + for (size_t o = 0; o < n; ) { + size_t l = u8_len((unsigned char)s[o]); + if (o + l > n) l = n - o; + push_piece(arr, s + o, l); + o += l; + } + } else { + const char* cur = s; + for (;;) { + const char* p = strstr(cur, sep); + push_piece(arr, cur, p ? (size_t)(p - cur) : strlen(cur)); + if (!p) break; + cur = p + sl; + } + } + } + tb_block_set_output(self, 0, tb_value_json(arr)); + tb_json_release(arr); + self->dirty = false; +} + +static void eval_contains(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64], b1[64]; + char* a = tb_string_lower(TXT(0)); + char* w = tb_string_lower(TXT(1)); + out_bool(self, a && w && strstr(a, w) != NULL); + free(a); free(w); +} + +static void eval_starts(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64], b1[64]; + const char* s = TXT(0); + const char* w = TXT(1); + out_bool(self, strncmp(s, w, strlen(w)) == 0); +} + +static void eval_ends(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64], b1[64]; + const char* s = TXT(0); + const char* w = TXT(1); + size_t n = strlen(s), m = strlen(w); + out_bool(self, m <= n && strcmp(s + n - m, w) == 0); +} + +static void eval_isnum(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + out_bool(self, tb_string_is_number(TXT(0))); +} + +static void eval_isempty(TinyBlocks_Block* self, TinyBlocks* rt) { + char b0[64]; + char* t = tb_string_trim(TXT(0)); + out_bool(self, !t || !t[0]); + free(t); +} + +/* -- Registro ------------------------------------------------------------- */ + +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 string_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Texto", + {207/255.f, 99/255.f, 207/255.f, 1.f}, + {170/255.f, 68/255.f, 170/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + TB_BLOCK_META("String.Upper", "tb_string_upper", "Texto em letras maiusculas"); + TB_BLOCK_META("String.Lower", "tb_string_lower", "Texto em letras minusculas"); + TB_BLOCK_META("String.Sub", "tb_string_sub", "Pedaco do texto da letra A ate a letra B"); + TB_BLOCK_META("String.Letter", "eval_letter", "A letra N do texto (1 = primeira)"); + TB_BLOCK_META("String.Length", "tb_string_length", "Quantas letras o texto tem"); + TB_BLOCK_META("String.Find", "tb_string_find", "Posicao do trecho no texto (0 = nao tem)"); + TB_BLOCK_META("String.Replace", "tb_string_replace", "Troca todas as ocorrencias de um trecho"); + TB_BLOCK_META("String.Trim", "tb_string_trim", "Tira os espacos do comeco e do fim"); + TB_BLOCK_META("String.Repeat", "eval_repeat", "Repete o texto N vezes"); + TB_BLOCK_META("String.Reverse", "tb_string_reverse", "Texto de tras para frente"); + TB_BLOCK_META("String.Split", "eval_split", "Divide o texto em uma lista pelo separador"); + TB_BLOCK_META("String.Contains", "eval_contains", "Verdadeiro se o texto contem o trecho (ignora maiusculas)"); + TB_BLOCK_META("String.StartsWith", "eval_starts", "Verdadeiro se o texto comeca com o trecho"); + TB_BLOCK_META("String.EndsWith", "eval_ends", "Verdadeiro se o texto termina com o trecho"); + TB_BLOCK_META("String.IsNumber", "tb_string_is_number", "Verdadeiro se o texto for um numero"); + TB_BLOCK_META("String.IsEmpty", "eval_isempty", "Verdadeiro se o texto estiver vazio (ou so espacos)"); + + static const TinyBlocks_SlotDesc t1[] = {{"texto", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc t2[] = {{"texto", TB_VALUE_TEXT}, {"trecho", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc t3[] = {{"texto", TB_VALUE_TEXT}, {"trecho", TB_VALUE_TEXT}, {"por", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc sub[] = {{"texto", TB_VALUE_TEXT}, {"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc tn[] = {{"texto", TB_VALUE_TEXT}, {"n", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc split[]= {{"texto", TB_VALUE_TEXT}, {"separador", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc int_out[] = {{"numero", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}}; + /* saidas terminadas em '?' = blocos booleanos (hexagonais no editor) */ + static const TinyBlocks_SlotDesc has_out[] = {{"contém?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc beg_out[] = {{"começa?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc end_out[] = {{"termina?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc num_out[] = {{"é número?", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc emp_out[] = {{"vazio?", TB_VALUE_INTEGER}}; + + return reg(rt, lib, "String.Upper", t1, 1, text_out, 1, eval_upper) + && reg(rt, lib, "String.Lower", t1, 1, text_out, 1, eval_lower) + && reg(rt, lib, "String.Sub", sub, 3, text_out, 1, eval_sub) + && reg(rt, lib, "String.Letter", tn, 2, text_out, 1, eval_letter) + && reg(rt, lib, "String.Length", t1, 1, int_out, 1, eval_length) + && reg(rt, lib, "String.Find", t2, 2, int_out, 1, eval_find) + && reg(rt, lib, "String.Replace", t3, 3, text_out, 1, eval_replace) + && reg(rt, lib, "String.Trim", t1, 1, text_out, 1, eval_trim) + && reg(rt, lib, "String.Repeat", tn, 2, text_out, 1, eval_repeat) + && reg(rt, lib, "String.Reverse", t1, 1, text_out, 1, eval_reverse) + && reg(rt, lib, "String.Split", split, 2, list_out, 1, eval_split) + && reg(rt, lib, "String.Contains", t2, 2, has_out, 1, eval_contains) + && reg(rt, lib, "String.StartsWith", t2, 2, beg_out, 1, eval_starts) + && reg(rt, lib, "String.EndsWith", t2, 2, end_out, 1, eval_ends) + && reg(rt, lib, "String.IsNumber", t1, 1, num_out, 1, eval_isnum) + && reg(rt, lib, "String.IsEmpty", t1, 1, emp_out, 1, eval_isempty); +} + +static void string_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(string, + "tinyblocks-string", + "1.0.0", + string_init, + string_deinit) + +const TinyBlocks_LibraryDescriptor* tb_string_get_library(void) { + return &_tb_lib_desc_string; +} diff --git a/libraries/tinyblocks-vector/Makefile b/libraries/tinyblocks-vector/Makefile new file mode 100644 index 0000000..3dcd4ee --- /dev/null +++ b/libraries/tinyblocks-vector/Makefile @@ -0,0 +1,29 @@ +# Makefile da library vector (categoria "Listas") +# Constroi build/libtinyblocks-vector.a e build/libtinyblocks-vector.so +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -I../../include -Iinclude + +OBJ := $(BUILD)/tb_vector.o +LIB_A := $(BUILD)/libtinyblocks-vector.a +LIB_SO := $(BUILD)/libtinyblocks-vector.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_vector.c include/tb_vector.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ -lm + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-vector/include/tb_vector.h b/libraries/tinyblocks-vector/include/tb_vector.h new file mode 100644 index 0000000..c218261 --- /dev/null +++ b/libraries/tinyblocks-vector/include/tb_vector.h @@ -0,0 +1,27 @@ +/* + * TinyBlocks - tb_vector.h + * Library tinyblocks-vector: listas dinamicas (como std::vector / as listas + * do Scratch). Registra a categoria "Listas"; os blocos se chamam List.* + * (Vector.* ja e o desenho vetorial do exemplo examples/vector). + * + * Uma lista e um array JSON (TB_VALUE_JSON), o mesmo formato de + * "itens da pasta" e Regex.Split. Os blocos sao funcionais: devolvem uma + * lista NOVA, e o programa guarda o resultado numa variavel: + * mude L para (adicione 5 ao fim de L) + * Um campo digitado tambem vira lista: "[1, 2, 3]" ou "maçã, banana". + * Posicoes comecam em 1. + */ +#ifndef TINYBLOCKS_VECTOR_H +#define TINYBLOCKS_VECTOR_H + +#include +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_vector_get_library(void); + +/* Converte um valor em lista (ref nova; libere com tb_json_release). + JSON array -> ele mesmo; texto "[...]" -> parse; "a, b" -> ["a","b"]; + numero -> [n]; vazio/outros -> []. */ +TB_API TinyBlocks_JsonValue* tb_vector_from_value(TinyBlocks_Value v); + +#endif /* TINYBLOCKS_VECTOR_H */ diff --git a/libraries/tinyblocks-vector/library.toml b/libraries/tinyblocks-vector/library.toml new file mode 100644 index 0000000..018a904 --- /dev/null +++ b/libraries/tinyblocks-vector/library.toml @@ -0,0 +1,15 @@ +# Metadados da library vector. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-vector" +version = "1.0.0" +category = "Listas" +description = "Listas (std::vector) - adicionar, inserir, remover, item N, ordenar, juntar" +color = [255, 102, 26, 255] +dark = [230, 77, 0, 255] + +[build] +sources = ["src/tb_vector.c"] +includes = ["include"] +shared = "build/libtinyblocks-vector.so" +static = "build/libtinyblocks-vector.a" +depends = [] diff --git a/libraries/tinyblocks-vector/src/tb_vector.c b/libraries/tinyblocks-vector/src/tb_vector.c new file mode 100644 index 0000000..972b7d2 --- /dev/null +++ b/libraries/tinyblocks-vector/src/tb_vector.c @@ -0,0 +1,516 @@ +/* + * TinyBlocks - tb_vector.c + * Categoria "Listas": List.Empty / Of / Range / Add / Insert / Remove / + * Replace / Item / Length / IndexOf / Slice / Reverse / Sort / Join / Sum e + * o booleano List.Contains. Listas sao arrays JSON imutaveis: cada bloco + * monta uma lista nova (ver tb_vector.h). + * + * Comparacao de itens como no Scratch: numeros pelo valor ("2" == 2.0) e + * textos sem diferenciar maiusculas. + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "tb_vector.h" + +#define LIST_MAX_RANGE 100000 + +/* -- Itens ---------------------------------------------------------------- */ + +static bool text_number(const char* s, double* out) { + while (isspace((unsigned char)*s)) s++; + if (!*s) return false; + char* e; + double d = strtod(s, &e); + if (e == s) return false; + while (isspace((unsigned char)*e)) e++; + if (*e) return false; + *out = d; + return true; +} + +/* Item JSON a partir de um texto digitado: numero vira numero */ +static TinyBlocks_JsonValue* item_from_text(const char* s) { + double d; + if (text_number(s, &d)) return tb_json_number(d); + return tb_json_string(s); +} + +/* Item JSON a partir de um valor de entrada (ref nova; NULL = sem valor) */ +static TinyBlocks_JsonValue* item_from_value(TinyBlocks_Value v) { + switch (v.kind) { + case TB_VALUE_INTEGER: return tb_json_number((double)v.as.integer); + case TB_VALUE_REAL: return tb_json_number(v.as.real); + case TB_VALUE_TEXT: return tb_json_string(v.as.text ? v.as.text : ""); + case TB_VALUE_JSON: if (v.as.json) tb_json_retain(v.as.json); return v.as.json; + default: return NULL; + } +} + +/* Valor de saida a partir de um item JSON */ +static TinyBlocks_Value value_from_item(const TinyBlocks_JsonValue* j) { + if (!j) return tb_value_text(""); + switch (tb_json_kind(j)) { + case TB_JSON_NUMBER: { + double d = tb_json_as_number(j, 0); + if (d == floor(d) && fabs(d) < 1e15) return tb_value_integer((int64_t)d); + return tb_value_real(d); + } + case TB_JSON_STRING: return tb_value_text(tb_json_as_string(j)); + case TB_JSON_BOOL: return tb_value_integer(tb_json_as_bool(j, false) ? 1 : 0); + case TB_JSON_NULL: return tb_value_text(""); + default: { + TinyBlocks_JsonValue* c = tb_json_clone(j); + TinyBlocks_Value v = tb_value_json(c); + tb_json_release(c); + return v; + } + } +} + +/* Texto do item (para juntar/comparar) */ +static void item_text(const TinyBlocks_JsonValue* j, char* out, size_t cap) { + out[0] = 0; + if (!j) return; + switch (tb_json_kind(j)) { + case TB_JSON_NUMBER: { + double d = tb_json_as_number(j, 0); + if (d == floor(d) && fabs(d) < 1e15) snprintf(out, cap, "%lld", (long long)d); + else snprintf(out, cap, "%g", d); + break; + } + case TB_JSON_STRING: snprintf(out, cap, "%s", tb_json_as_string(j)); break; + case TB_JSON_BOOL: snprintf(out, cap, "%s", tb_json_as_bool(j, false) ? "1" : "0"); break; + case TB_JSON_NULL: break; + default: { + char* s = tb_json_stringify(j); + snprintf(out, cap, "%s", s ? s : ""); + free(s); + } + } +} + +static bool item_number(const TinyBlocks_JsonValue* j, double* d) { + if (!j) return false; + if (tb_json_kind(j) == TB_JSON_NUMBER) { *d = tb_json_as_number(j, 0); return true; } + if (tb_json_kind(j) == TB_JSON_STRING) return text_number(tb_json_as_string(j), d); + return false; +} + +static bool item_equal(const TinyBlocks_JsonValue* a, const TinyBlocks_JsonValue* b) { + double x, y; + if (item_number(a, &x) && item_number(b, &y)) return x == y; + char sa[512], sb[512]; + item_text(a, sa, sizeof(sa)); + item_text(b, sb, sizeof(sb)); + return strcasecmp(sa, sb) == 0; +} + +/* -- Listas --------------------------------------------------------------- */ + +static void push_owned(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) { + if (!item) return; + tb_json_array_push(arr, item); + tb_json_release(item); +} + +/* "maçã, banana" -> ["maçã", "banana"]; itens numericos viram numero */ +static TinyBlocks_JsonValue* list_from_csv(const char* s) { + TinyBlocks_JsonValue* arr = tb_json_array(); + if (!arr) return NULL; + while (*s) { + const char* e = strchr(s, ','); + size_t n = e ? (size_t)(e - s) : strlen(s); + while (n && isspace((unsigned char)*s)) { s++; n--; } + while (n && isspace((unsigned char)s[n - 1])) n--; + char* piece = malloc(n + 1); + if (piece) { + memcpy(piece, s, n); + piece[n] = 0; + push_owned(arr, item_from_text(piece)); + free(piece); + } + if (!e) break; + s = e + 1; + } + return arr; +} + +TB_API TinyBlocks_JsonValue* tb_vector_from_value(TinyBlocks_Value v) { + if (v.kind == TB_VALUE_JSON && v.as.json && tb_json_kind(v.as.json) == TB_JSON_ARRAY) { + tb_json_retain(v.as.json); + return v.as.json; + } + if (v.kind == TB_VALUE_TEXT && v.as.text) { + const char* s = v.as.text; + while (isspace((unsigned char)*s)) s++; + if (!*s) return tb_json_array(); + if (*s == '[') { + TinyBlocks_JsonValue* j = tb_json_parse(s, NULL, 0); + if (j && tb_json_kind(j) == TB_JSON_ARRAY) return j; + if (j) tb_json_release(j); + } + return list_from_csv(s); + } + TinyBlocks_JsonValue* arr = tb_json_array(); + if (arr && (v.kind == TB_VALUE_INTEGER || v.kind == TB_VALUE_REAL || + (v.kind == TB_VALUE_JSON && v.as.json))) + push_owned(arr, item_from_value(v)); + return arr; +} + +/* Copia os itens [from, to) de src para uma lista nova */ +static TinyBlocks_JsonValue* list_copy(const TinyBlocks_JsonValue* src, uint32_t from, uint32_t to) { + TinyBlocks_JsonValue* arr = tb_json_array(); + uint32_t n = src ? tb_json_array_length(src) : 0; + if (to > n) to = n; + for (uint32_t i = from; arr && i < to; i++) push_owned(arr, tb_json_array_get(src, i)); + return arr; +} + +/* -- Entradas/saidas ------------------------------------------------------ */ + +static TinyBlocks_JsonValue* in_list(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + return tb_vector_from_value(tb_block_get_input(self, rt, i)); +} + +static long long in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_INTEGER) return v.as.integer; + if (v.kind == TB_VALUE_REAL) return (long long)llround(v.as.real); + if (v.kind == TB_VALUE_TEXT && v.as.text) return strtoll(v.as.text, NULL, 10); + return 0; +} + +static TinyBlocks_JsonValue* in_item(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_JsonValue* it = item_from_value(tb_block_get_input(self, rt, i)); + return it ? it : tb_json_string(""); +} + +/* Toma a referencia de arr */ +static void out_list(TinyBlocks_Block* self, TinyBlocks_JsonValue* arr) { + if (!arr) arr = tb_json_array(); + tb_block_set_output(self, 0, tb_value_json(arr)); + tb_json_release(arr); + self->dirty = false; +} + +static void out_int(TinyBlocks_Block* self, long long n) { + tb_block_set_output(self, 0, tb_value_integer(n)); + self->dirty = false; +} + +/* -- Blocos --------------------------------------------------------------- */ + +static void eval_empty(TinyBlocks_Block* self, TinyBlocks* rt) { + (void)rt; + out_list(self, tb_json_array()); +} + +/* "lista com A B C": campos vazios ficam de fora */ +static void eval_of(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* arr = tb_json_array(); + for (uint32_t i = 0; arr && i < 3; i++) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_NONE || (v.kind == TB_VALUE_TEXT && (!v.as.text || !v.as.text[0]))) + continue; + push_owned(arr, item_from_value(v)); + } + out_list(self, arr); +} + +/* "números de A até B" (inclusivo, passo 1 ou -1) */ +static void eval_range(TinyBlocks_Block* self, TinyBlocks* rt) { + long long a = in_int(self, rt, 0), b = in_int(self, rt, 1); + long long step = a <= b ? 1 : -1; + long long n = (b - a) * step + 1; + if (n > LIST_MAX_RANGE) n = LIST_MAX_RANGE; + TinyBlocks_JsonValue* arr = tb_json_array(); + for (long long i = 0; arr && i < n; i++) push_owned(arr, tb_json_number((double)(a + i * step))); + out_list(self, arr); +} + +static void eval_add(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + TinyBlocks_JsonValue* arr = list_copy(src, 0, UINT32_MAX); + if (arr) push_owned(arr, in_item(self, rt, 1)); + tb_json_release(src); + out_list(self, arr); +} + +/* "insira X na posição N de L": N fora da faixa encaixa no comeco/fim */ +static void eval_insert(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + uint32_t n = src ? tb_json_array_length(src) : 0; + long long pos = in_int(self, rt, 2); + if (pos < 1) pos = 1; + if (pos > (long long)n + 1) pos = (long long)n + 1; + TinyBlocks_JsonValue* arr = list_copy(src, 0, (uint32_t)(pos - 1)); + if (arr) { + push_owned(arr, in_item(self, rt, 1)); + for (uint32_t i = (uint32_t)(pos - 1); i < n; i++) push_owned(arr, tb_json_array_get(src, i)); + } + tb_json_release(src); + out_list(self, arr); +} + +static void eval_remove(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + uint32_t n = src ? tb_json_array_length(src) : 0; + long long k = in_int(self, rt, 1); + TinyBlocks_JsonValue* arr = tb_json_array(); + for (uint32_t i = 0; arr && i < n; i++) + if ((long long)i + 1 != k) push_owned(arr, tb_json_array_get(src, i)); + tb_json_release(src); + out_list(self, arr); +} + +static void eval_replace(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + uint32_t n = src ? tb_json_array_length(src) : 0; + long long k = in_int(self, rt, 1); + TinyBlocks_JsonValue* arr = tb_json_array(); + for (uint32_t i = 0; arr && i < n; i++) { + if ((long long)i + 1 == k) push_owned(arr, in_item(self, rt, 2)); + else push_owned(arr, tb_json_array_get(src, i)); + } + tb_json_release(src); + out_list(self, arr); +} + +static void eval_item(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + long long k = in_int(self, rt, 1); + uint32_t n = src ? tb_json_array_length(src) : 0; + TinyBlocks_JsonValue* it = (k >= 1 && k <= (long long)n) ? tb_json_array_get(src, (uint32_t)(k - 1)) : NULL; + tb_block_set_output(self, 0, value_from_item(it)); + if (it) tb_json_release(it); + tb_json_release(src); + self->dirty = false; +} + +static void eval_length(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + out_int(self, src ? tb_json_array_length(src) : 0); + tb_json_release(src); +} + +/* posicao do item (1..n), 0 se nao estiver na lista */ +static long long find_item(const TinyBlocks_JsonValue* src, const TinyBlocks_JsonValue* want) { + uint32_t n = src ? tb_json_array_length(src) : 0; + for (uint32_t i = 0; i < n; i++) { + TinyBlocks_JsonValue* it = tb_json_array_get(src, i); + bool eq = item_equal(it, want); + if (it) tb_json_release(it); + if (eq) return (long long)i + 1; + } + return 0; +} + +static void eval_index_of(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + TinyBlocks_JsonValue* want = in_item(self, rt, 1); + out_int(self, find_item(src, want)); + tb_json_release(want); + tb_json_release(src); +} + +static void eval_contains(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + TinyBlocks_JsonValue* want = in_item(self, rt, 1); + out_int(self, find_item(src, want) > 0 ? 1 : 0); + tb_json_release(want); + tb_json_release(src); +} + +/* "itens A a B de L" (inclusivo, cortado aos limites) */ +static void eval_slice(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + long long a = in_int(self, rt, 1), b = in_int(self, rt, 2); + if (a < 1) a = 1; + TinyBlocks_JsonValue* arr = (b >= a) ? list_copy(src, (uint32_t)(a - 1), (uint32_t)(b > UINT32_MAX ? UINT32_MAX : b)) + : tb_json_array(); + tb_json_release(src); + out_list(self, arr); +} + +static void eval_reverse(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + uint32_t n = src ? tb_json_array_length(src) : 0; + TinyBlocks_JsonValue* arr = tb_json_array(); + for (uint32_t i = n; arr && i > 0; i--) push_owned(arr, tb_json_array_get(src, i - 1)); + tb_json_release(src); + out_list(self, arr); +} + +/* Ordem: numeros (pelo valor) antes de textos (sem diferenciar maiusculas) */ +static int cmp_items(const void* pa, const void* pb) { + const TinyBlocks_JsonValue* a = *(TinyBlocks_JsonValue* const*)pa; + const TinyBlocks_JsonValue* b = *(TinyBlocks_JsonValue* const*)pb; + double x, y; + bool na = item_number(a, &x), nb = item_number(b, &y); + if (na && nb) return x < y ? -1 : x > y ? 1 : 0; + if (na != nb) return na ? -1 : 1; + char sa[512], sb[512]; + item_text(a, sa, sizeof(sa)); + item_text(b, sb, sizeof(sb)); + return strcasecmp(sa, sb); +} + +static void eval_sort(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + uint32_t n = src ? tb_json_array_length(src) : 0; + TinyBlocks_JsonValue** items = n ? malloc(n * sizeof(*items)) : NULL; + TinyBlocks_JsonValue* arr = tb_json_array(); + if (items) { + for (uint32_t i = 0; i < n; i++) items[i] = tb_json_array_get(src, i); + qsort(items, n, sizeof(*items), cmp_items); + for (uint32_t i = 0; i < n; i++) { + if (arr) push_owned(arr, items[i]); + else if (items[i]) tb_json_release(items[i]); + } + free(items); + } + tb_json_release(src); + out_list(self, arr); +} + +static void eval_join(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + TinyBlocks_Value sv = tb_block_get_input(self, rt, 1); + const char* sep = (sv.kind == TB_VALUE_TEXT && sv.as.text) ? sv.as.text : ""; + uint32_t n = src ? tb_json_array_length(src) : 0; + size_t cap = 256, len = 0, sl = strlen(sep); + char* out = malloc(cap); + if (out) out[0] = 0; + for (uint32_t i = 0; out && i < n; i++) { + char t[512]; + TinyBlocks_JsonValue* it = tb_json_array_get(src, i); + item_text(it, t, sizeof(t)); + if (it) tb_json_release(it); + size_t tl = strlen(t), need = len + (i ? sl : 0) + tl + 1; + if (need > cap) { + while (cap < need) cap *= 2; + char* no = realloc(out, cap); + if (!no) break; + out = no; + } + if (i) { memcpy(out + len, sep, sl); len += sl; } + memcpy(out + len, t, tl + 1); + len += tl; + } + tb_block_set_output(self, 0, tb_value_text(out ? out : "")); + free(out); + tb_json_release(src); + self->dirty = false; +} + +static void eval_sum(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_JsonValue* src = in_list(self, rt, 0); + uint32_t n = src ? tb_json_array_length(src) : 0; + double s = 0; + for (uint32_t i = 0; i < n; i++) { + TinyBlocks_JsonValue* it = tb_json_array_get(src, i); + double d; + if (item_number(it, &d)) s += d; + if (it) tb_json_release(it); + } + tb_json_release(src); + if (s == floor(s) && fabs(s) < 1e15) tb_block_set_output(self, 0, tb_value_integer((int64_t)s)); + else tb_block_set_output(self, 0, tb_value_real(s)); + self->dirty = false; +} + +/* -- Registro ------------------------------------------------------------- */ + +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 vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "Listas", + {255/255.f, 102/255.f, 26/255.f, 1.f}, + {230/255.f, 77/255.f, 0/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + TB_BLOCK_META("List.Empty", "eval_empty", "Uma lista sem itens"); + TB_BLOCK_META("List.Of", "eval_of", "Lista com ate 3 itens (campos vazios ficam de fora)"); + TB_BLOCK_META("List.Range", "eval_range", "Lista com os numeros de A ate B"); + TB_BLOCK_META("List.Add", "eval_add", "Nova lista com o item no fim"); + TB_BLOCK_META("List.Insert", "eval_insert", "Nova lista com o item na posicao N"); + TB_BLOCK_META("List.Remove", "eval_remove", "Nova lista sem o item N"); + TB_BLOCK_META("List.Replace", "eval_replace", "Nova lista com o item N trocado"); + TB_BLOCK_META("List.Item", "eval_item", "O item N da lista (1 = primeiro)"); + TB_BLOCK_META("List.Length", "eval_length", "Quantos itens a lista tem"); + TB_BLOCK_META("List.IndexOf", "eval_index_of", "Posicao do item na lista (0 = nao tem)"); + TB_BLOCK_META("List.Contains", "eval_contains", "Verdadeiro se a lista tiver o item"); + TB_BLOCK_META("List.Slice", "eval_slice", "Pedaco da lista do item A ao item B"); + TB_BLOCK_META("List.Reverse", "eval_reverse", "Lista de tras para frente"); + TB_BLOCK_META("List.Sort", "eval_sort", "Lista em ordem (numeros, depois textos)"); + TB_BLOCK_META("List.Join", "eval_join", "Texto com os itens separados pelo separador"); + TB_BLOCK_META("List.Sum", "eval_sum", "Soma dos itens numericos"); + + /* listas e itens chegam como "qualquer" (TB_VALUE_NONE): o campo + digitado vira numero ou texto, e o texto pode ser "[1,2]" ou "a, b" */ + static const TinyBlocks_SlotDesc l1[] = {{"lista", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc li[] = {{"lista", TB_VALUE_NONE}, {"item", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc ln[] = {{"lista", TB_VALUE_NONE}, {"n", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc lin[] = {{"lista", TB_VALUE_NONE}, {"item", TB_VALUE_NONE}, {"n", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc lni[] = {{"lista", TB_VALUE_NONE}, {"n", TB_VALUE_INTEGER}, {"item", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc lab[] = {{"lista", TB_VALUE_NONE}, {"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc lsep[] = {{"lista", TB_VALUE_NONE}, {"separador", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc of_in[] = {{"a", TB_VALUE_NONE}, {"b", TB_VALUE_NONE}, {"c", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc rng[] = {{"de", TB_VALUE_INTEGER}, {"ate", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc list_out[] = {{"lista", TB_VALUE_JSON}}; + static const TinyBlocks_SlotDesc item_out[] = {{"item", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc int_out[] = {{"numero", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc num_out[] = {{"numero", TB_VALUE_NONE}}; + static const TinyBlocks_SlotDesc text_out[] = {{"texto", TB_VALUE_TEXT}}; + /* saida terminada em '?' = bloco booleano (hexagonal no editor) */ + static const TinyBlocks_SlotDesc has_out[] = {{"contém?", TB_VALUE_INTEGER}}; + + return reg(rt, lib, "List.Empty", NULL, 0, list_out, 1, eval_empty) + && reg(rt, lib, "List.Of", of_in, 3, list_out, 1, eval_of) + && reg(rt, lib, "List.Range", rng, 2, list_out, 1, eval_range) + && reg(rt, lib, "List.Add", li, 2, list_out, 1, eval_add) + && reg(rt, lib, "List.Insert", lin, 3, list_out, 1, eval_insert) + && reg(rt, lib, "List.Remove", ln, 2, list_out, 1, eval_remove) + && reg(rt, lib, "List.Replace", lni, 3, list_out, 1, eval_replace) + && reg(rt, lib, "List.Item", ln, 2, item_out, 1, eval_item) + && reg(rt, lib, "List.Length", l1, 1, int_out, 1, eval_length) + && reg(rt, lib, "List.IndexOf", li, 2, int_out, 1, eval_index_of) + && reg(rt, lib, "List.Contains", li, 2, has_out, 1, eval_contains) + && reg(rt, lib, "List.Slice", lab, 3, list_out, 1, eval_slice) + && reg(rt, lib, "List.Reverse", l1, 1, list_out, 1, eval_reverse) + && reg(rt, lib, "List.Sort", l1, 1, list_out, 1, eval_sort) + && reg(rt, lib, "List.Join", lsep, 2, text_out, 1, eval_join) + && reg(rt, lib, "List.Sum", l1, 1, num_out, 1, eval_sum); +} + +static void vector_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + (void)rt; (void)lib; +} + +TINYBLOCKS_DEFINE_LIBRARY(vector, + "tinyblocks-vector", + "1.0.0", + vector_init, + vector_deinit) + +const TinyBlocks_LibraryDescriptor* tb_vector_get_library(void) { + return &_tb_lib_desc_vector; +} diff --git a/tests/os_fs_test.c b/tests/os_fs_test.c new file mode 100644 index 0000000..3f95c98 --- /dev/null +++ b/tests/os_fs_test.c @@ -0,0 +1,145 @@ +/* + * os_fs_test.c - testa tinyblocks-os (informacoes do sistema) e os blocos + * de pasta do tinyblocks-fs (FS.ListDir / ListCount / ListItem / IsFile / + * IsDir / Exists). + */ +#include +#include +#include +#include +#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 TinyBlocks* rt; + +/* Cria o bloco, preenche as entradas (texto/inteiro) e avalia */ +static TinyBlocks_Block* run(const char* type, const char* a, long long b) { + TinyBlocks_TypeBlock* t = tb_rt_find_type(rt, type); + if (!t) return NULL; + TinyBlocks_Block* blk = tb_block_create(rt, t); + if (a) { + TinyBlocks_Value v = tb_value_text(a); + tb_block_set_default(blk, 0, v); + tb_value_free(&v); + } + if (b >= 0) { + TinyBlocks_Value v = tb_value_integer(b); + tb_block_set_default(blk, 1, v); + tb_value_free(&v); + } + tb_block_eval(blk, rt); + return blk; +} + +static long long out_int(TinyBlocks_Block* b) { + return (b && b->outputs[0].kind == TB_VALUE_INTEGER) ? b->outputs[0].as.integer : -1; +} +static const char* out_text(TinyBlocks_Block* b) { + return (b && b->outputs[0].kind == TB_VALUE_TEXT && b->outputs[0].as.text) ? b->outputs[0].as.text : ""; +} + +static void touch(const char* p) { + FILE* f = fopen(p, "wb"); + if (f) { fputs("x", f); fclose(f); } +} + +int main(void) { + tinyblocks_init(&rt, NULL); + TinyBlocks_LibraryBlock* fs = tb_library_register(rt, tb_fs_get_library()); + TinyBlocks_LibraryBlock* os = tb_library_register(rt, tb_os_get_library()); + CHECK(fs && os, "libraries fs e os registradas"); + const TinyBlocks_Category* cat = os ? tb_library_category(os) : NULL; + CHECK(cat && !strcmp(cat->name, "Sistema"), "categoria 'Sistema'"); + + /* -- tinyblocks-os -- */ + char buf[512]; + tb_os_name(buf, sizeof(buf)); + CHECK(buf[0], "tb_os_name devolve um nome"); + TinyBlocks_Block* b = run("OS.Name", NULL, -1); + CHECK(!strcmp(out_text(b), buf), "OS.Name igual a tb_os_name"); + tb_block_destroy(b, rt); + b = run("OS.Distro", NULL, -1); + CHECK(out_text(b)[0], "OS.Distro devolve texto"); + tb_block_destroy(b, rt); + b = run("OS.Version", NULL, -1); + CHECK(out_text(b)[0], "OS.Version devolve a versao do kernel"); + tb_block_destroy(b, rt); + b = run("OS.Arch", NULL, -1); + CHECK(out_text(b)[0], "OS.Arch devolve a arquitetura"); + tb_block_destroy(b, rt); + b = run("OS.User", NULL, -1); + CHECK(out_text(b)[0], "OS.User devolve o usuario"); + tb_block_destroy(b, rt); + b = run("OS.Cpus", NULL, -1); + CHECK(out_int(b) >= 1, "OS.Cpus >= 1"); + tb_block_destroy(b, rt); + b = run("OS.MemoryMB", NULL, -1); + CHECK(out_int(b) > 0, "OS.MemoryMB > 0"); + tb_block_destroy(b, rt); + b = run("OS.Is", buf, -1); + CHECK(out_int(b) == 1, "OS.Is(nome do SO) verdadeiro"); + tb_block_destroy(b, rt); + b = run("OS.Is", "SistemaQueNaoExiste", -1); + CHECK(out_int(b) == 0, "OS.Is(outro) falso"); + tb_block_destroy(b, rt); + TinyBlocks_TypeBlock* tis = tb_rt_find_type(rt, "OS.Is"); + CHECK(tis && tis->output_desc_count == 1 && + tis->output_descs[0].name[strlen(tis->output_descs[0].name) - 1] == '?', + "OS.Is declara saida booleana ('?')"); + + /* -- tinyblocks-fs: pastas -- */ + char dir[] = "/tmp/tb_osfs_XXXXXX"; + CHECK(mkdtemp(dir) != NULL, "pasta temporaria"); + char p[256]; + snprintf(p, sizeof(p), "%s/b.txt", dir); touch(p); + snprintf(p, sizeof(p), "%s/A.json", dir); touch(p); + snprintf(p, sizeof(p), "%s/sub", dir); mkdir(p, 0755); + + b = run("FS.ListCount", dir, -1); + CHECK(out_int(b) == 3, "FS.ListCount = 3"); + tb_block_destroy(b, rt); + + b = run("FS.ListDir", dir, -1); + bool list_ok = b && b->outputs[0].kind == TB_VALUE_JSON; + if (list_ok) { + TinyBlocks_JsonValue* arr = b->outputs[0].as.json; + list_ok = tb_json_array_length(arr) == 3; + TinyBlocks_JsonValue* first = list_ok ? tb_json_array_get(arr, 0) : NULL; + list_ok = list_ok && first && !strcmp(tb_json_as_string(first), "A.json"); + if (first) tb_json_release(first); + } + CHECK(list_ok, "FS.ListDir devolve lista ordenada [A.json, b.txt, sub]"); + tb_block_destroy(b, rt); + + b = run("FS.ListItem", dir, 2); + CHECK(!strcmp(out_text(b), "b.txt"), "FS.ListItem(2) = b.txt"); + tb_block_destroy(b, rt); + b = run("FS.ListItem", dir, 9); + CHECK(!strcmp(out_text(b), ""), "FS.ListItem fora da faixa = vazio"); + tb_block_destroy(b, rt); + + snprintf(p, sizeof(p), "%s/b.txt", dir); + b = run("FS.IsFile", p, -1); CHECK(out_int(b) == 1, "FS.IsFile(arquivo) verdadeiro"); tb_block_destroy(b, rt); + b = run("FS.IsDir", p, -1); CHECK(out_int(b) == 0, "FS.IsDir(arquivo) falso"); tb_block_destroy(b, rt); + b = run("FS.Exists", p, -1); CHECK(out_int(b) == 1, "FS.Exists(arquivo) verdadeiro"); tb_block_destroy(b, rt); + remove(p); + snprintf(p, sizeof(p), "%s/sub", dir); + b = run("FS.IsDir", p, -1); CHECK(out_int(b) == 1, "FS.IsDir(pasta) verdadeiro"); tb_block_destroy(b, rt); + b = run("FS.IsFile", p, -1); CHECK(out_int(b) == 0, "FS.IsFile(pasta) falso"); tb_block_destroy(b, rt); + rmdir(p); + snprintf(p, sizeof(p), "%s/A.json", dir); + remove(p); + b = run("FS.Exists", p, -1); CHECK(out_int(b) == 0, "FS.Exists(apagado) falso"); tb_block_destroy(b, rt); + rmdir(dir); + + tinyblocks_deinit(&rt); + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +} diff --git a/tests/stdlib_test.c b/tests/stdlib_test.c new file mode 100644 index 0000000..4bca377 --- /dev/null +++ b/tests/stdlib_test.c @@ -0,0 +1,181 @@ +/* + * stdlib_test.c - testa tinyblocks-string (Texto), tinyblocks-number + * (Números) e tinyblocks-vector (Listas) pelos blocos, como o editor usa. + */ +#include +#include +#include +#include +#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 TinyBlocks* rt; +static TinyBlocks_Block* last; + +/* Avalia `type` com ate 3 entradas dadas como texto (NULL = vazio). + O texto e convertido como o editor faz com um campo digitado. */ +static TinyBlocks_Value* run(const char* type, const char* a, const char* b, const char* c) { + if (last) { tb_block_destroy(last, rt); last = NULL; } + TinyBlocks_TypeBlock* t = tb_rt_find_type(rt, type); + if (!t) { printf(" (tipo %s nao existe)\n", type); return NULL; } + last = tb_block_create(rt, t); + const char* in[3] = { a, b, c }; + for (uint32_t i = 0; i < 3 && i < t->input_desc_count; i++) { + if (!in[i]) continue; + TinyBlocks_Value v; + char* e; + switch (t->input_descs[i].expected_kind) { + case TB_VALUE_INTEGER: v = tb_value_integer(strtoll(in[i], NULL, 10)); break; + case TB_VALUE_REAL: v = tb_value_real(strtod(in[i], NULL)); break; + case TB_VALUE_NONE: { + long long iv = strtoll(in[i], &e, 10); + if (in[i][0] && !*e) { v = tb_value_integer(iv); break; } + double dv = strtod(in[i], &e); + v = (in[i][0] && !*e) ? tb_value_real(dv) : tb_value_text(in[i]); + break; + } + default: v = tb_value_text(in[i]); break; + } + tb_block_set_default(last, i, v); + tb_value_free(&v); + } + tb_block_eval(last, rt); + return &last->outputs[0]; +} + +static bool is_text(TinyBlocks_Value* v, const char* s) { + return v && v->kind == TB_VALUE_TEXT && v->as.text && strcmp(v->as.text, s) == 0; +} +static bool is_int(TinyBlocks_Value* v, long long n) { + return v && v->kind == TB_VALUE_INTEGER && v->as.integer == n; +} +static bool is_real(TinyBlocks_Value* v, double d) { + return v && v->kind == TB_VALUE_REAL && fabs(v->as.real - d) < 1e-9; +} +/* Lista igual ao JSON esperado (ex.: "[1,2,\"a\"]") */ +static bool is_list(TinyBlocks_Value* v, const char* json) { + if (!v || v->kind != TB_VALUE_JSON || !v->as.json) return false; + char* s = tb_json_stringify(v->as.json); + char* exp_s = NULL; + TinyBlocks_JsonValue* e = tb_json_parse(json, NULL, 0); + if (e) exp_s = tb_json_stringify(e); + bool ok = s && exp_s && strcmp(s, exp_s) == 0; + if (!ok) printf(" obtido %s, esperado %s\n", s ? s : "(null)", exp_s ? exp_s : json); + free(s); free(exp_s); + if (e) tb_json_release(e); + return ok; +} + +int main(void) { + tinyblocks_init(&rt, NULL); + TinyBlocks_LibraryBlock* ls = tb_library_register(rt, tb_string_get_library()); + TinyBlocks_LibraryBlock* ln = tb_library_register(rt, tb_number_get_library()); + TinyBlocks_LibraryBlock* lv = tb_library_register(rt, tb_vector_get_library()); + CHECK(ls && ln && lv, "libraries string, number e vector registradas"); + CHECK(!strcmp(tb_library_category(ls)->name, "Texto") && + !strcmp(tb_library_category(ln)->name, "Números") && + !strcmp(tb_library_category(lv)->name, "Listas"), "categorias Texto / Números / Listas"); + + /* -- Texto -- */ + CHECK(is_text(run("String.Upper", "maçã", NULL, NULL), "MAÇÃ"), "maiúsculas com acento"); + CHECK(is_text(run("String.Lower", "ÁRVORE", NULL, NULL), "árvore"), "minúsculas com acento"); + CHECK(is_int(run("String.Length", "maçã", NULL, NULL), 4), "número de letras conta UTF-8 (maçã = 4)"); + CHECK(is_text(run("String.Letter", "maçã", "3", NULL), "ç"), "letra 3 de maçã = ç"); + CHECK(is_text(run("String.Sub", "TinyBlocks", "5", "10"), "Blocks"), "letras 5 a 10"); + CHECK(is_text(run("String.Sub", "abc", "2", "99"), "bc"), "trecho cortado no fim"); + CHECK(is_int(run("String.Find", "pão de açúcar", "açúcar", NULL), 8), "posição conta letras"); + CHECK(is_int(run("String.Find", "abc", "z", NULL), 0), "posição 0 quando não acha"); + CHECK(is_text(run("String.Replace", "banana", "a", "o"), "bonono"), "troca todas as ocorrências"); + CHECK(is_text(run("String.Trim", " olá \n", NULL, NULL), "olá"), "apara espaços"); + CHECK(is_text(run("String.Repeat", "ab", "3", NULL), "ababab"), "repete 3 vezes"); + CHECK(is_text(run("String.Reverse", "maçã", NULL, NULL), "ãçam"), "inverte por letra (UTF-8)"); + CHECK(is_list(run("String.Split", "a,,b", ",", NULL), "[\"a\",\"\",\"b\"]"), "divide mantendo item vazio"); + CHECK(is_list(run("String.Split", "ñá", "", NULL), "[\"ñ\",\"á\"]"), "separador vazio = uma letra por item"); + CHECK(is_int(run("String.Contains", "Maçã Verde", "maçã", NULL), 1), "contém ignora maiúsculas"); + CHECK(is_int(run("String.StartsWith", "foto.png", "foto", NULL), 1), "começa com"); + CHECK(is_int(run("String.EndsWith", "foto.png", ".jpg", NULL), 0), "não termina com .jpg"); + CHECK(is_int(run("String.IsNumber", " 3.5 ", NULL, NULL), 1) && + is_int(run("String.IsNumber", "3a", NULL, NULL), 0), "é número?"); + CHECK(is_int(run("String.IsEmpty", " ", NULL, NULL), 1), "só espaços está vazio"); + + /* -- Números -- */ + CHECK(is_real(run("Number.Div", "10", "4", NULL), 2.5), "10 ÷ 4 = 2.5"); + CHECK(is_int(run("Number.Div", "10", "2", NULL), 5), "resultado exato sai inteiro"); + CHECK(is_int(run("Number.Div", "1", "0", NULL), 0), "divisão por 0 dá 0"); + CHECK(is_int(run("Number.Pow", "2", "10", NULL), 1024), "2 elevado a 10"); + CHECK(is_int(run("Number.Sqrt", "16", NULL, NULL), 4), "raiz de 16"); + CHECK(is_int(run("Number.Round", "2.5", NULL, NULL), 3) && + is_int(run("Number.Floor", "-2.5", NULL, NULL), -3) && + is_int(run("Number.Ceil", "2.1", NULL, NULL), 3), "arredondamentos"); + CHECK(is_real(run("Number.RoundTo", "3.14159", "2", NULL), 3.14), "arredonda com 2 casas"); + CHECK(is_int(run("Number.Sin", "90", NULL, NULL), 1) && + is_int(run("Number.Sin", "180", NULL, NULL), 0) && + is_int(run("Number.Cos", "0", NULL, NULL), 1), "trigonometria em graus (sen 180 = 0)"); + CHECK(is_int(run("Number.Atan", "1", NULL, NULL), 45), "arco-tangente de 1 = 45"); + CHECK(is_int(run("Number.Log10", "1000", NULL, NULL), 3), "log de 1000"); + CHECK(is_real(run("Number.Pi", NULL, NULL, NULL), 3.14159265358979), "pi"); + TinyBlocks_Value* r = run("Number.Random", "5", "6", NULL); + CHECK(r && r->kind == TB_VALUE_REAL && r->as.real >= 5 && r->as.real < 6, "aleatório real entre 5 e 6"); + CHECK(is_int(run("Number.Clamp", "150", "0", "100"), 100), "limite entre 0 e 100"); + CHECK(is_text(run("Number.Format", "3.14159", "2", NULL), "3.14"), "formata com 2 casas"); + CHECK(is_int(run("Number.IsEven", "4", NULL, NULL), 1) && + is_int(run("Number.IsEven", "7", NULL, NULL), 0), "é par?"); + CHECK(is_int(run("Number.IsPrime", "97", NULL, NULL), 1) && + is_int(run("Number.IsPrime", "91", NULL, NULL), 0) && + is_int(run("Number.IsPrime", "1", NULL, NULL), 0), "é primo?"); + CHECK(is_int(run("Number.IsInteger", "2.5", NULL, NULL), 0), "2.5 não é inteiro"); + + /* -- Listas -- */ + CHECK(is_list(run("List.Empty", NULL, NULL, NULL), "[]"), "lista vazia"); + CHECK(is_list(run("List.Of", "maçã", "2", NULL), "[\"maçã\",2]"), "lista com (campo vazio fica de fora)"); + CHECK(is_list(run("List.Range", "3", "1", NULL), "[3,2,1]"), "números de 3 até 1"); + CHECK(is_list(run("List.Add", "1, 2", "3", NULL), "[1,2,3]"), "texto 'a, b' vira lista; adiciona no fim"); + CHECK(is_list(run("List.Add", "[\"x\"]", "y", NULL), "[\"x\",\"y\"]"), "texto JSON vira lista"); + CHECK(is_list(run("List.Insert", "a, c", "b", "2"), "[\"a\",\"b\",\"c\"]"), "insere na posição 2"); + CHECK(is_list(run("List.Insert", "a", "z", "99"), "[\"a\",\"z\"]"), "posição além do fim insere no fim"); + CHECK(is_list(run("List.Remove", "a, b, c", "2", NULL), "[\"a\",\"c\"]"), "remove o item 2"); + CHECK(is_list(run("List.Replace", "a, b, c", "2", "B"), "[\"a\",\"B\",\"c\"]"), "troca o item 2"); + CHECK(is_text(run("List.Item", "maçã, banana", "2", NULL), "banana"), "item 2"); + CHECK(is_int(run("List.Item", "10, 20", "1", NULL), 10), "item numérico sai como número"); + CHECK(is_text(run("List.Item", "a", "5", NULL), ""), "item fora da faixa = vazio"); + CHECK(is_int(run("List.Length", "a, b, c", NULL, NULL), 3), "tamanho da lista"); + CHECK(is_int(run("List.IndexOf", "a, B, c", "b", NULL), 2), "posição ignora maiúsculas"); + CHECK(is_int(run("List.IndexOf", "1, 2.0, 3", "2", NULL), 2), "posição compara números pelo valor"); + CHECK(is_int(run("List.Contains", "maçã, uva", "uva", NULL), 1) && + is_int(run("List.Contains", "maçã, uva", "pera", NULL), 0), "contém o item?"); + CHECK(is_list(run("List.Slice", "1,2,3,4,5", "2", "4"), "[2,3,4]"), "itens 2 a 4"); + CHECK(is_list(run("List.Reverse", "1, 2, 3", NULL, NULL), "[3,2,1]"), "inverte a lista"); + CHECK(is_list(run("List.Sort", "banana, 10, Abacate, 2", NULL, NULL), "[2,10,\"Abacate\",\"banana\"]"), + "ordena números antes de textos"); + CHECK(is_text(run("List.Join", "a, b, c", " - ", NULL), "a - b - c"), "junta com separador"); + CHECK(is_real(run("List.Sum", "1, 2.5, x", NULL, NULL), 3.5), "soma ignora itens não numéricos"); + + /* Encadeia: lista da pasta de Texto vira lista de Listas */ + { + TinyBlocks_TypeBlock* ts = tb_rt_find_type(rt, "String.Split"); + TinyBlocks_TypeBlock* tl = tb_rt_find_type(rt, "List.Length"); + TinyBlocks_Block* bs = tb_block_create(rt, ts); + TinyBlocks_Block* bl = tb_block_create(rt, tl); + TinyBlocks_Value v = tb_value_text("x;y;z"), sep = tb_value_text(";"); + tb_block_set_default(bs, 0, v); tb_block_set_default(bs, 1, sep); + tb_value_free(&v); tb_value_free(&sep); + tb_block_connect(bl, 0, bs, 0); + tb_block_eval(bl, rt); + CHECK(bl->outputs[0].kind == TB_VALUE_INTEGER && bl->outputs[0].as.integer == 3, + "divida (Texto) conectado em tamanho da lista (Listas)"); + tb_block_destroy(bl, rt); + tb_block_destroy(bs, rt); + } + + if (last) tb_block_destroy(last, rt); + tinyblocks_deinit(&rt); + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +}