Adiciona libraries toml/fs, metadados .toml e build por library

- tinyblocks-toml: lexer + parser TOML (include/lexeme.h, include/ast.h,
  src/lexer.c, src/parser.c) e bloco Toml.Get.
- tinyblocks-fs: categoria "Arquivos" com FS.Open/Read/Write/Append/Tell/Close.
- library.toml em cada library com metadados (categoria, cor, descricao) e
  receita de build, sem precisar embutir isso no .so.
- Makefiles proprios por library com build/ local; Makefile raiz delega.
- Palco (tb_stage) movido para o core; pen deixa de depender do editor, o
  que torna os .so arrastaveis.
- Editor linka com -rdynamic para resolver simbolos do core em .so via dlopen.
- Testes: test-toml (parser) e test-plugin (dlopen de .so standalone).
This commit is contained in:
mguinhos committed 2026-10-20 19:38:58 -03:00
1 parent 90d47bf8a0
commit dc23b92d15
48 files changed
+2405 -744

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
# Makefile da library toml (parser de TOML + metadados)
# Constroi build/libtinyblocks-toml.a e build/libtinyblocks-toml.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
OBJS := $(BUILD)/lexer.o $(BUILD)/parser.o $(BUILD)/tb_toml.o
LIB_A := $(BUILD)/libtinyblocks-toml.a
LIB_SO := $(BUILD)/libtinyblocks-toml.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(BUILD)/lexer.o: src/lexer.c include/lexeme.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(BUILD)/parser.o: src/parser.c include/ast.h include/lexeme.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(BUILD)/tb_toml.o: src/tb_toml.c include/tb_toml.h include/ast.h include/lexeme.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^
clean:
$(RM) -r $(BUILD)
+78
View File
@@ -0,0 +1,78 @@
/*
* TinyBlocks - tinyblocks-toml
* ast.h: arvore sintatica e leitura de documentos TOML.
*/
#ifndef TB_TOML_AST_H
#define TB_TOML_AST_H
#include <stddef.h>
#include <stdbool.h>
#include "lexeme.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
TOML_STRING,
TOML_INTEGER,
TOML_FLOAT,
TOML_BOOL,
TOML_DATETIME,
TOML_ARRAY,
TOML_TABLE
} TomlValueKind;
typedef struct TomlValue TomlValue;
typedef struct TomlKeyVal TomlKeyVal;
struct TomlKeyVal {
char* key;
TomlValue* value;
TomlKeyVal* next;
};
struct TomlValue {
TomlValueKind kind;
int line, col;
union {
char* string;
long long integer;
double real;
bool boolean;
struct { TomlValue** items; size_t count, cap; } array;
struct { TomlKeyVal* head, *tail; size_t count; } table;
} as;
};
typedef struct {
TomlValue* root; /* tabela raiz */
} TomlDoc;
/* Parser (texto em memoria / arquivo). Em erro preenche err. */
TomlDoc* toml_parse(const char* src, TomlLexError* err);
TomlDoc* toml_parse_file(const char* path, TomlLexError* err);
void toml_free(TomlDoc* doc);
/* Navegacao */
const TomlValue* toml_table_get(const TomlValue* table, const char* key);
const TomlValue* toml_path_get(const TomlValue* root, const char* dotted);
const TomlValue* toml_array_get(const TomlValue* arr, size_t i);
size_t toml_array_count(const TomlValue* arr);
size_t toml_table_count(const TomlValue* table);
const TomlKeyVal* toml_table_head(const TomlValue* table);
/* Conversoes com valor padrao */
const char* toml_as_string(const TomlValue* v, const char* def);
long long toml_as_int(const TomlValue* v, long long def);
double toml_as_float(const TomlValue* v, double def);
bool toml_as_bool(const TomlValue* v, bool def);
/* Escreve a arvore em stdout (debug) */
void toml_dump(const TomlValue* v, int indent);
#ifdef __cplusplus
}
#endif
#endif /* TB_TOML_AST_H */
@@ -0,0 +1,68 @@
/*
* TinyBlocks - tinyblocks-toml
* lexeme.h: tipos de token e lexer de TOML.
*/
#ifndef TB_TOML_LEXEME_H
#define TB_TOML_LEXEME_H
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
TL_EOF = 0,
TL_ERROR,
TL_NEWLINE,
TL_LBRACKET, /* [ */
TL_RBRACKET, /* ] */
TL_LBRACE, /* { */
TL_RBRACE, /* } */
TL_EQUALS, /* = */
TL_COMMA, /* , */
TL_DOT, /* . */
TL_BARE, /* chave simples */
TL_STRING, /* string (basica/literal) */
TL_INTEGER,
TL_FLOAT,
TL_BOOL,
TL_DATETIME
} TomlLexKind;
typedef struct {
TomlLexKind kind;
const char* start; /* inicio no fonte (nao NUL-terminado) */
size_t len; /* tamanho no fonte */
int line, col;
char* text; /* string decodificada (TL_STRING), malloc */
long long ival;
double fval;
bool bval;
} Lexeme;
typedef struct {
Lexeme* items;
size_t count, cap;
} LexemeList;
typedef struct {
bool ok;
char msg[256];
int line, col;
} TomlLexError;
/* Tokeniza o texto inteiro. Em erro retorna false e preenche *err. */
bool toml_lex(const char* src, LexemeList* out, TomlLexError* err);
/* Libera a lista e os textos decodificados */
void toml_lexemes_free(LexemeList* list);
const char* toml_lexeme_kind_name(TomlLexKind kind);
#ifdef __cplusplus
}
#endif
#endif /* TB_TOML_LEXEME_H */
@@ -0,0 +1,27 @@
/*
* TinyBlocks - tb_toml.h
* Library tinyblocks-toml: parser de TOML (lexer + AST) e metadados de
* library. Tambem expoe o bloco Toml.Get para scripts.
*/
#ifndef TINYBLOCKS_TOML_H
#define TINYBLOCKS_TOML_H
#include <tinyblocks/tinyblocks.h>
#include "lexeme.h"
#include "ast.h"
#ifdef __cplusplus
extern "C" {
#endif
TB_API const TinyBlocks_LibraryDescriptor* tb_toml_get_library(void);
/* Le um valor escalar de um arquivo .toml (ex.: "library.category").
* Retorna o valor em 'out' ou o default. Util para metadados de library. */
TB_API const char* tb_toml_file_get(const char* path, const char* dotted, const char* def);
#ifdef __cplusplus
}
#endif
#endif /* TINYBLOCKS_TOML_H */
+15
View File
@@ -0,0 +1,15 @@
# Metadados da library toml. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-toml"
version = "1.0.0"
category = "TOML"
description = "Parser de TOML e metadados de library"
color = [158, 112, 219, 255]
dark = [125, 51, 178, 255]
[build]
sources = ["src/lexer.c", "src/parser.c", "src/tb_toml.c"]
includes = ["include"]
shared = "build/libtinyblocks-toml.so"
static = "build/libtinyblocks-toml.a"
depends = []
+343
View File
@@ -0,0 +1,343 @@
/*
* TinyBlocks - tinyblocks-toml
* lexer.c: tokenizacao de TOML (subset: chaves, strings, numeros, datas,
* arrays, tabelas e tabelas inline).
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "lexeme.h"
typedef struct {
const char* p;
int line, col;
LexemeList* out;
TomlLexError* err;
} Lexer;
static bool is_bare_char(int c) {
return isalnum((unsigned char)c) || c == '_' || c == '-';
}
static void adv(Lexer* L) {
if (*L->p == '\n') { L->line++; L->col = 1; }
else L->col++;
L->p++;
}
static bool push(Lexer* L, TomlLexKind kind, const char* start, size_t len) {
if (L->out->count >= L->out->cap) {
size_t nc = L->out->cap ? L->out->cap * 2 : 64;
Lexeme* p = (Lexeme*)realloc(L->out->items, nc * sizeof(Lexeme));
if (!p) return false;
L->out->items = p; L->out->cap = nc;
}
Lexeme* t = &L->out->items[L->out->count++];
memset(t, 0, sizeof(*t));
t->kind = kind;
t->start = start;
t->len = len;
t->line = L->line;
t->col = L->col;
return true;
}
static bool fail(Lexer* L, const char* msg) {
if (L->err) {
L->err->ok = false;
snprintf(L->err->msg, sizeof(L->err->msg), "%s", msg);
L->err->line = L->line;
L->err->col = L->col;
}
return false;
}
/* buffer de texto decodificado */
typedef struct { char* p; size_t n, cap; } Buf;
static bool buf_put(Buf* b, char c) {
if (b->n + 1 >= b->cap) {
size_t nc = b->cap ? b->cap * 2 : 32;
char* p = (char*)realloc(b->p, nc);
if (!p) return false;
b->p = p; b->cap = nc;
}
b->p[b->n++] = c;
b->p[b->n] = 0;
return true;
}
static int hexval(int c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
static bool utf8_put(Buf* b, unsigned cp) {
if (cp <= 0x7F) return buf_put(b, (char)cp);
if (cp <= 0x7FF) {
return buf_put(b, (char)(0xC0 | (cp >> 6))) &&
buf_put(b, (char)(0x80 | (cp & 0x3F)));
}
if (cp <= 0xFFFF) {
return buf_put(b, (char)(0xE0 | (cp >> 12))) &&
buf_put(b, (char)(0x80 | ((cp >> 6) & 0x3F))) &&
buf_put(b, (char)(0x80 | (cp & 0x3F)));
}
return buf_put(b, (char)(0xF0 | (cp >> 18))) &&
buf_put(b, (char)(0x80 | ((cp >> 12) & 0x3F))) &&
buf_put(b, (char)(0x80 | ((cp >> 6) & 0x3F))) &&
buf_put(b, (char)(0x80 | (cp & 0x3F)));
}
/* Le a string basica/literal (single ou multiline). Assume p no delimitador. */
static bool lex_string(Lexer* L) {
const char* start = L->p;
char q = *L->p;
bool multi = (L->p[1] == q && L->p[2] == q);
Buf b = {0};
adv(L);
if (multi) { adv(L); adv(L); }
if (multi && (*L->p == '\r' || *L->p == '\n')) {
if (*L->p == '\r' && L->p[1] == '\n') adv(L);
adv(L);
}
for (;;) {
char c = *L->p;
if (!c) { free(b.p); return fail(L, "string nao terminada"); }
if (multi) {
if (c == q && L->p[1] == q && L->p[2] == q) { adv(L); adv(L); adv(L); break; }
} else {
if (c == q) { adv(L); break; }
if (c == '\n') { free(b.p); return fail(L, "quebra de linha em string"); }
}
if (q == '\'' ) { /* literal: sem escapes */
buf_put(&b, c); adv(L); continue;
}
if (c == '\\') {
adv(L);
char e = *L->p;
if (!multi && (e == '\n' || e == 0)) { free(b.p); return fail(L, "escape invalido"); }
switch (e) {
case 'b': buf_put(&b, '\b'); adv(L); break;
case 't': buf_put(&b, '\t'); adv(L); break;
case 'n': buf_put(&b, '\n'); adv(L); break;
case 'f': buf_put(&b, '\f'); adv(L); break;
case 'r': buf_put(&b, '\r'); adv(L); break;
case '"': buf_put(&b, '"'); adv(L); break;
case '\\': buf_put(&b, '\\'); adv(L); break;
case 'u': case 'U': {
int n = (e == 'u') ? 4 : 8;
adv(L);
unsigned cp = 0;
for (int i = 0; i < n; i++) {
int h = hexval((unsigned char)*L->p);
if (h < 0) { free(b.p); return fail(L, "escape unicode invalido"); }
cp = cp * 16 + (unsigned)h; adv(L);
}
utf8_put(&b, cp);
break;
}
default:
if (multi && (e == '\n' || e == '\r' || e == ' ' || e == '\t')) {
/* continua a linha: come a barra e espacos em branco */
while (*L->p == ' ' || *L->p == '\t' || *L->p == '\r') adv(L);
if (*L->p == '\n') adv(L);
while (*L->p == ' ' || *L->p == '\t' || *L->p == '\r' || *L->p == '\n') adv(L);
break;
}
free(b.p); return fail(L, "escape invalido");
}
continue;
}
buf_put(&b, c); adv(L);
}
if (!push(L, TL_STRING, start, (size_t)(L->p - start))) { free(b.p); return false; }
L->out->items[L->out->count - 1].text = b.p ? b.p : (char*)calloc(1, 1);
return true;
}
/* Tenta casar uma data/hora a partir de p; retorna o tamanho casado. */
static size_t scan_datetime(const char* p) {
const char* s = p;
int digits = 0;
while (isdigit((unsigned char)*s)) { s++; digits++; }
if (digits == 4 && *s == '-') {
const char* d = s + 1; int m = 0;
while (isdigit((unsigned char)*d)) { d++; m++; }
if (m != 2 || *d != '-') return 0;
d++; int dd = 0;
while (isdigit((unsigned char)*d)) { d++; dd++; }
if (dd != 2) return 0;
s = d;
if (*s == 'T' || *s == 't' || *s == ' ') {
const char* t = s + 1;
int h = 0; while (isdigit((unsigned char)*t)) { t++; h++; }
if (h == 2 && *t == ':') {
t++; int mi = 0; while (isdigit((unsigned char)*t)) { t++; mi++; }
if (mi == 2 && *t == ':') {
t++; int se = 0; while (isdigit((unsigned char)*t)) { t++; se++; }
if (se == 2) {
if (*t == '.') { t++; while (isdigit((unsigned char)*t)) t++; }
if (*t == 'Z' || *t == 'z') t++;
else if ((*t == '+' || *t == '-')) {
t++; int hh = 0; while (isdigit((unsigned char)*t)) { t++; hh++; }
if (hh == 2 && *t == ':') { t++; int mm = 0; while (isdigit((unsigned char)*t)) { t++; mm++; } }
}
}
}
}
s = t;
}
return (size_t)(s - p);
}
if (digits == 2) {
const char* t = s;
if (*t == ':') {
t++; int mi = 0; while (isdigit((unsigned char)*t)) { t++; mi++; }
if (mi == 2 && *t == ':') {
t++; int se = 0; while (isdigit((unsigned char)*t)) { t++; se++; }
if (se == 2) {
if (*t == '.') { t++; while (isdigit((unsigned char)*t)) t++; }
return (size_t)(t - p);
}
}
}
}
return 0;
}
static bool lex_number(Lexer* L) {
const char* start = L->p;
size_t dt = scan_datetime(L->p);
if (dt) {
while ((size_t)(L->p - start) < dt) adv(L);
return push(L, TL_DATETIME, start, dt);
}
if (*L->p == '+' || *L->p == '-') adv(L);
/* inf / nan */
if (strncmp(L->p, "inf", 3) == 0 || strncmp(L->p, "nan", 3) == 0) {
adv(L); adv(L); adv(L);
Lexeme tok; bool ok = push(L, TL_FLOAT, start, (size_t)(L->p - start));
if (!ok) return false;
tok = L->out->items[L->out->count - 1];
tok.fval = (start[0] == '-') ? -0.0 : 0.0; /* inf/nan: valor 0 */
L->out->items[L->out->count - 1] = tok;
return true;
}
bool ishex = (L->p[0] == '0' && (L->p[1] == 'x' || L->p[1] == 'o' || L->p[1] == 'b'));
bool isfloat = false;
if (ishex) {
int base = L->p[1] == 'x' ? 16 : (L->p[1] == 'o' ? 8 : 2);
adv(L); adv(L);
while (is_bare_char((unsigned char)*L->p) && *L->p != '-') adv(L);
char buf[128]; size_t n = (size_t)(L->p - start);
if (n >= sizeof(buf)) n = sizeof(buf) - 1;
memcpy(buf, start, n); buf[n] = 0;
/* remove underscores e prefixo */
char clean[128]; size_t cn = 0;
for (size_t i = 0; buf[i] && cn < sizeof(clean) - 1; i++)
if (buf[i] != '_') clean[cn++] = buf[i];
clean[cn] = 0;
if (!push(L, TL_INTEGER, start, (size_t)(L->p - start))) return false;
L->out->items[L->out->count - 1].ival = strtoll(clean, NULL, base);
return true;
}
while (isdigit((unsigned char)*L->p) || *L->p == '_') adv(L);
if (*L->p == '.') { isfloat = true; adv(L); while (isdigit((unsigned char)*L->p) || *L->p == '_') adv(L); }
if (*L->p == 'e' || *L->p == 'E') {
isfloat = true; adv(L);
if (*L->p == '+' || *L->p == '-') adv(L);
while (isdigit((unsigned char)*L->p) || *L->p == '_') adv(L);
}
char buf[128]; size_t n = (size_t)(L->p - start);
if (n >= sizeof(buf)) n = sizeof(buf) - 1;
memcpy(buf, start, n); buf[n] = 0;
char clean[128]; size_t cn = 0;
for (size_t i = 0; buf[i] && cn < sizeof(clean) - 1; i++)
if (buf[i] != '_') clean[cn++] = buf[i];
clean[cn] = 0;
if (!push(L, isfloat ? TL_FLOAT : TL_INTEGER, start, (size_t)(L->p - start))) return false;
Lexeme* t = &L->out->items[L->out->count - 1];
if (isfloat) t->fval = strtod(clean, NULL);
else t->ival = strtoll(clean, NULL, 10);
return true;
}
bool toml_lex(const char* src, LexemeList* out, TomlLexError* err) {
Lexer L = { src, 1, 1, out, err };
if (err) { err->ok = true; err->msg[0] = 0; err->line = err->col = 0; }
for (;;) {
char c = *L.p;
if (c == 0) { if (!push(&L, TL_EOF, L.p, 0)) return false; break; }
if (c == ' ' || c == '\t') { adv(&L); continue; }
if (c == '\r') { adv(&L); if (*L.p == '\n') adv(&L); if (!push(&L, TL_NEWLINE, L.p, 0)) return false; continue; }
if (c == '\n') { adv(&L); if (!push(&L, TL_NEWLINE, L.p, 0)) return false; continue; }
if (c == '#') { while (*L.p && *L.p != '\n') adv(&L); continue; }
if (c == '"' || c == '\'') { if (!lex_string(&L)) return false; continue; }
switch (c) {
case '[': adv(&L); if (!push(&L, TL_LBRACKET, L.p - 1, 1)) return false; continue;
case ']': adv(&L); if (!push(&L, TL_RBRACKET, L.p - 1, 1)) return false; continue;
case '{': adv(&L); if (!push(&L, TL_LBRACE, L.p - 1, 1)) return false; continue;
case '}': adv(&L); if (!push(&L, TL_RBRACE, L.p - 1, 1)) return false; continue;
case '=': adv(&L); if (!push(&L, TL_EQUALS, L.p - 1, 1)) return false; continue;
case ',': adv(&L); if (!push(&L, TL_COMMA, L.p - 1, 1)) return false; continue;
case '.': adv(&L); if (!push(&L, TL_DOT, L.p - 1, 1)) return false; continue;
default: break;
}
if (c == '+' || c == '-' || isdigit((unsigned char)c)) { if (!lex_number(&L)) return false; continue; }
if (is_bare_char((unsigned char)c)) {
const char* start = L.p;
while (is_bare_char((unsigned char)*L.p)) adv(&L);
size_t n = (size_t)(L.p - start);
TomlLexKind k = TL_BARE;
if (n == 4 && strncmp(start, "true", 4) == 0) k = TL_BOOL;
else if (n == 5 && strncmp(start, "false", 5) == 0) k = TL_BOOL;
else if ((n == 3 && (strncmp(start, "inf", 3) == 0 || strncmp(start, "nan", 3) == 0))) k = TL_FLOAT;
if (!push(&L, k, start, n)) return false;
Lexeme* t = &L.out->items[L.out->count - 1];
if (k == TL_BOOL) t->bval = (start[0] == 't');
if (k == TL_FLOAT) t->fval = 0.0;
continue;
}
return fail(&L, "caractere inesperado");
}
return true;
}
void toml_lexemes_free(LexemeList* list) {
if (!list) return;
for (size_t i = 0; i < list->count; i++) free(list->items[i].text);
free(list->items);
list->items = NULL; list->count = list->cap = 0;
}
const char* toml_lexeme_kind_name(TomlLexKind kind) {
switch (kind) {
case TL_EOF: return "EOF";
case TL_ERROR: return "ERROR";
case TL_NEWLINE: return "NEWLINE";
case TL_LBRACKET: return "[";
case TL_RBRACKET: return "]";
case TL_LBRACE: return "{";
case TL_RBRACE: return "}";
case TL_EQUALS: return "=";
case TL_COMMA: return ",";
case TL_DOT: return ".";
case TL_BARE: return "BARE";
case TL_STRING: return "STRING";
case TL_INTEGER: return "INTEGER";
case TL_FLOAT: return "FLOAT";
case TL_BOOL: return "BOOL";
case TL_DATETIME: return "DATETIME";
}
return "?";
}
+447
View File
@@ -0,0 +1,447 @@
/*
* TinyBlocks - tinyblocks-toml
* parser.c: parser descendente recursivo de TOML sobre a lista de lexemas.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "ast.h"
typedef struct {
const Lexeme* toks;
size_t n, i;
TomlValue* root;
TomlValue* cur; /* tabela corrente (headers) */
TomlLexError* err;
} Parser;
static const Lexeme* peek(Parser* P) { return &P->toks[P->i]; }
static const Lexeme* advance(Parser* P) {
const Lexeme* t = &P->toks[P->i];
if (P->i + 1 < P->n) P->i++;
return t;
}
static bool at(Parser* P, TomlLexKind k) { return peek(P)->kind == k; }
static bool accept(Parser* P, TomlLexKind k) {
if (!at(P, k)) return false;
advance(P);
return true;
}
static TomlValue* vnew(TomlValueKind k, int line, int col) {
TomlValue* v = (TomlValue*)calloc(1, sizeof(TomlValue));
if (!v) return NULL;
v->kind = k; v->line = line; v->col = col;
return v;
}
static TomlValue* vtable(int line, int col) { return vnew(TOML_TABLE, line, col); }
static char* dup_range(const char* s, size_t n) {
char* p = (char*)malloc(n + 1);
if (!p) return NULL;
memcpy(p, s, n); p[n] = 0;
return p;
}
/* chave de um token (bare/string/numero/bool/data) */
static char* token_key(const Lexeme* t) {
if (t->kind == TL_STRING && t->text) return dup_range(t->text, strlen(t->text));
return dup_range(t->start, t->len);
}
static void value_free(TomlValue* v) {
if (!v) return;
switch (v->kind) {
case TOML_STRING: free(v->as.string); break;
case TOML_DATETIME: free(v->as.string); break;
case TOML_ARRAY:
for (size_t i = 0; i < v->as.array.count; i++) value_free(v->as.array.items[i]);
free(v->as.array.items);
break;
case TOML_TABLE: {
TomlKeyVal* kv = v->as.table.head;
while (kv) { TomlKeyVal* nx = kv->next; free(kv->key); value_free(kv->value); free(kv); kv = nx; }
break;
}
default: break;
}
free(v);
}
static TomlKeyVal* table_find(const TomlValue* t, const char* key) {
if (!t || t->kind != TOML_TABLE) return NULL;
for (TomlKeyVal* kv = t->as.table.head; kv; kv = kv->next)
if (strcmp(kv->key, key) == 0) return kv;
return NULL;
}
static bool table_set(TomlValue* t, char* key, TomlValue* val) {
TomlKeyVal* kv = table_find(t, key);
if (kv) {
free(key);
value_free(kv->value);
kv->value = val;
return true;
}
kv = (TomlKeyVal*)calloc(1, sizeof(TomlKeyVal));
if (!kv) { free(key); value_free(val); return false; }
kv->key = key; kv->value = val;
if (t->as.table.tail) t->as.table.tail->next = kv;
else t->as.table.head = kv;
t->as.table.tail = kv;
t->as.table.count++;
return true;
}
static TomlValue* table_child(TomlValue* t, const char* key, bool create) {
TomlKeyVal* kv = table_find(t, key);
if (kv) {
if (kv->value->kind == TOML_TABLE) return kv->value;
return NULL;
}
if (!create) return NULL;
TomlValue* child = vtable(t->line, t->col);
if (!child) return NULL;
if (!table_set(t, dup_range(key, strlen(key)), child)) return NULL;
return child;
}
/* [[a.b]]: obtem/cria o array em 't' com a chave, devolve o array */
static TomlValue* table_array(TomlValue* t, const char* key) {
TomlKeyVal* kv = table_find(t, key);
if (kv && kv->value->kind == TOML_ARRAY) return kv->value;
if (kv) return NULL;
TomlValue* arr = vnew(TOML_ARRAY, t->line, t->col);
if (!arr) return NULL;
if (!table_set(t, dup_range(key, strlen(key)), arr)) return NULL;
return arr;
}
static bool array_push(TomlValue* arr, TomlValue* v) {
if (arr->as.array.count >= arr->as.array.cap) {
size_t nc = arr->as.array.cap ? arr->as.array.cap * 2 : 8;
TomlValue** p = (TomlValue**)realloc(arr->as.array.items, nc * sizeof(TomlValue*));
if (!p) return false;
arr->as.array.items = p; arr->as.array.cap = nc;
}
arr->as.array.items[arr->as.array.count++] = v;
return true;
}
static bool fail(Parser* P, const Lexeme* t, const char* msg) {
if (P->err) {
P->err->ok = false;
snprintf(P->err->msg, sizeof(P->err->msg), "%s", msg);
P->err->line = t->line;
P->err->col = t->col;
}
return false;
}
static void skip_newlines(Parser* P) { while (at(P, TL_NEWLINE)) advance(P); }
/* le uma sequencia de chaves separadas por ponto: a, b.c */
#define MAX_KEYS 16
static int parse_key_path(Parser* P, char* keys[MAX_KEYS]) {
int n = 0;
for (;;) {
const Lexeme* t = peek(P);
if (t->kind != TL_BARE && t->kind != TL_STRING &&
t->kind != TL_INTEGER && t->kind != TL_FLOAT &&
t->kind != TL_BOOL && t->kind != TL_DATETIME) {
fail(P, t, "chave esperada"); return -1;
}
if (n >= MAX_KEYS) { fail(P, t, "chaves demais"); return -1; }
keys[n++] = token_key(t);
advance(P);
if (!accept(P, TL_DOT)) break;
}
return n;
}
static void free_keys(char* keys[], int n) { for (int i = 0; i < n; i++) free(keys[i]); }
static TomlValue* parse_value(Parser* P);
static TomlValue* parse_array(Parser* P) {
const Lexeme* open = advance(P); /* [ */
TomlValue* arr = vnew(TOML_ARRAY, open->line, open->col);
if (!arr) return NULL;
for (;;) {
skip_newlines(P);
if (accept(P, TL_RBRACKET)) return arr;
TomlValue* v = parse_value(P);
if (!v) { value_free(arr); return NULL; }
array_push(arr, v);
skip_newlines(P);
if (accept(P, TL_COMMA)) continue;
if (at(P, TL_RBRACKET)) continue;
fail(P, peek(P), "esperado , ou ]");
value_free(arr); return NULL;
}
}
static TomlValue* parse_inline_table(Parser* P) {
const Lexeme* open = advance(P); /* { */
TomlValue* t = vtable(open->line, open->col);
if (!t) return NULL;
for (;;) {
if (accept(P, TL_RBRACE)) return t;
char* keys[MAX_KEYS];
int n = parse_key_path(P, keys);
if (n < 0) { value_free(t); return NULL; }
if (!accept(P, TL_EQUALS)) {
fail(P, peek(P), "esperado =");
free_keys(keys, n); value_free(t); return NULL;
}
TomlValue* v = parse_value(P);
if (!v) { free_keys(keys, n); value_free(t); return NULL; }
TomlValue* dst = t;
for (int j = 0; j < n - 1 && dst; j++) dst = table_child(dst, keys[j], true);
if (!dst) { free_keys(keys, n); value_free(v); value_free(t); return NULL; }
table_set(dst, keys[n - 1], v); /* consome keys[n-1] */
for (int j = 0; j < n - 1; j++) free(keys[j]);
if (accept(P, TL_COMMA)) continue;
if (at(P, TL_RBRACE)) continue;
fail(P, peek(P), "esperado , ou }");
value_free(t); return NULL;
}
}
static TomlValue* parse_value(Parser* P) {
const Lexeme* t = peek(P);
switch (t->kind) {
case TL_STRING: {
advance(P);
TomlValue* v = vnew(TOML_STRING, t->line, t->col);
if (!v) return NULL;
v->as.string = dup_range(t->text ? t->text : "", t->text ? strlen(t->text) : 0);
return v;
}
case TL_INTEGER: {
advance(P);
TomlValue* v = vnew(TOML_INTEGER, t->line, t->col);
if (v) v->as.integer = t->ival;
return v;
}
case TL_FLOAT: {
advance(P);
TomlValue* v = vnew(TOML_FLOAT, t->line, t->col);
if (v) v->as.real = t->fval;
return v;
}
case TL_BOOL: {
advance(P);
TomlValue* v = vnew(TOML_BOOL, t->line, t->col);
if (v) v->as.boolean = t->bval;
return v;
}
case TL_DATETIME: {
advance(P);
TomlValue* v = vnew(TOML_DATETIME, t->line, t->col);
if (v) v->as.string = dup_range(t->start, t->len);
return v;
}
case TL_LBRACKET:
return parse_array(P);
case TL_LBRACE:
return parse_inline_table(P);
default:
fail(P, t, "valor esperado");
return NULL;
}
}
/* [a.b] / [[a.b]] */
static bool parse_table_header(Parser* P) {
const Lexeme* open = advance(P); /* [ */
bool array = accept(P, TL_LBRACKET);
char* keys[MAX_KEYS];
int n = parse_key_path(P, keys);
if (n < 0) return false;
if (!accept(P, TL_RBRACKET)) { fail(P, peek(P), "esperado ]"); free_keys(keys, n); return false; }
if (array && !accept(P, TL_RBRACKET)) { fail(P, peek(P), "esperado ]]"); free_keys(keys, n); return false; }
TomlValue* t = P->root;
for (int j = 0; j < n - 1 && t; j++) t = table_child(t, keys[j], true);
if (!t) { free_keys(keys, n); return true; }
if (array) {
TomlValue* arr = table_array(t, keys[n - 1]);
if (!arr) { free_keys(keys, n); fail(P, open, "array de tabelas invalido"); return false; }
TomlValue* elem = vtable(open->line, open->col);
if (!elem) { free_keys(keys, n); return false; }
array_push(arr, elem);
P->cur = elem;
} else {
TomlValue* child = table_child(t, keys[n - 1], true);
if (!child) { free_keys(keys, n); fail(P, open, "tabela invalida"); return false; }
P->cur = child;
}
free_keys(keys, n);
return true;
}
static bool parse_keyval(Parser* P) {
char* keys[MAX_KEYS];
int n = parse_key_path(P, keys);
if (n < 0) return false;
if (!accept(P, TL_EQUALS)) { fail(P, peek(P), "esperado ="); free_keys(keys, n); return false; }
TomlValue* v = parse_value(P);
if (!v) { free_keys(keys, n); return false; }
TomlValue* dst = P->cur ? P->cur : P->root;
for (int j = 0; j < n - 1 && dst; j++) dst = table_child(dst, keys[j], true);
if (!dst) { free_keys(keys, n); value_free(v); return false; }
table_set(dst, keys[n - 1], v); /* consome keys[n-1] */
for (int j = 0; j < n - 1; j++) free(keys[j]);
return true;
}
TomlDoc* toml_parse(const char* src, TomlLexError* err) {
LexemeList toks = {0};
if (!toml_lex(src, &toks, err)) { toml_lexemes_free(&toks); return NULL; }
Parser P = { toks.items, toks.count, 0, NULL, NULL, err };
P.root = vtable(1, 1);
P.cur = P.root;
if (!P.root) { toml_lexemes_free(&toks); return NULL; }
bool ok = true;
for (;;) {
skip_newlines(&P);
if (at(&P, TL_EOF)) break;
if (at(&P, TL_LBRACKET)) { if (!parse_table_header(&P)) { ok = false; break; } }
else { if (!parse_keyval(&P)) { ok = false; break; } }
if (!accept(&P, TL_NEWLINE) && !at(&P, TL_EOF)) {
fail(&P, peek(&P), "esperado quebra de linha");
ok = false; break;
}
}
toml_lexemes_free(&toks);
if (!ok) { value_free(P.root); return NULL; }
TomlDoc* doc = (TomlDoc*)calloc(1, sizeof(TomlDoc));
if (!doc) { value_free(P.root); return NULL; }
doc->root = P.root;
return doc;
}
TomlDoc* toml_parse_file(const char* path, TomlLexError* err) {
FILE* f = fopen(path, "rb");
if (!f) {
if (err) { err->ok = false; snprintf(err->msg, sizeof(err->msg), "nao abriu %s", path); err->line = err->col = 0; }
return NULL;
}
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
if (sz < 0 || sz > (long)(64 * 1024 * 1024)) { fclose(f); return NULL; }
char* buf = (char*)malloc((size_t)sz + 1);
if (!buf) { fclose(f); return NULL; }
size_t rd = fread(buf, 1, (size_t)sz, f);
buf[rd] = 0;
fclose(f);
TomlDoc* doc = toml_parse(buf, err);
free(buf);
return doc;
}
void toml_free(TomlDoc* doc) {
if (!doc) return;
value_free(doc->root);
free(doc);
}
/* -- Navegacao ----------------------------------------------------------- */
const TomlValue* toml_table_get(const TomlValue* table, const char* key) {
TomlKeyVal* kv = table_find(table, key);
return kv ? kv->value : NULL;
}
const TomlValue* toml_path_get(const TomlValue* root, const char* dotted) {
if (!root || !dotted) return NULL;
const TomlValue* t = root;
const char* p = dotted;
char part[128];
while (*p) {
size_t n = 0;
while (*p && *p != '.' && n < sizeof(part) - 1) part[n++] = *p++;
part[n] = 0;
if (t && t->kind == TOML_ARRAY) {
bool digits = part[0] != 0;
for (const char* q = part; *q; q++) if (!isdigit((unsigned char)*q)) digits = false;
t = digits ? toml_array_get(t, (size_t)strtoul(part, NULL, 10)) : NULL;
} else {
t = toml_table_get(t, part);
}
if (!t) return NULL;
if (*p == '.') p++;
}
return t;
}
const TomlValue* toml_array_get(const TomlValue* arr, size_t i) {
if (!arr || arr->kind != TOML_ARRAY || i >= arr->as.array.count) return NULL;
return arr->as.array.items[i];
}
size_t toml_array_count(const TomlValue* arr) {
return (arr && arr->kind == TOML_ARRAY) ? arr->as.array.count : 0;
}
size_t toml_table_count(const TomlValue* table) {
return (table && table->kind == TOML_TABLE) ? table->as.table.count : 0;
}
const TomlKeyVal* toml_table_head(const TomlValue* table) {
return (table && table->kind == TOML_TABLE) ? table->as.table.head : NULL;
}
const char* toml_as_string(const TomlValue* v, const char* def) {
if (!v) return def;
if (v->kind == TOML_STRING || v->kind == TOML_DATETIME) return v->as.string;
return def;
}
long long toml_as_int(const TomlValue* v, long long def) {
if (v && v->kind == TOML_INTEGER) return v->as.integer;
return def;
}
double toml_as_float(const TomlValue* v, double def) {
if (!v) return def;
if (v->kind == TOML_FLOAT) return v->as.real;
if (v->kind == TOML_INTEGER) return (double)v->as.integer;
return def;
}
bool toml_as_bool(const TomlValue* v, bool def) {
if (v && v->kind == TOML_BOOL) return v->as.boolean;
return def;
}
static void indent(int n) { for (int i = 0; i < n; i++) fputs(" ", stdout); }
void toml_dump(const TomlValue* v, int depth) {
if (!v) return;
switch (v->kind) {
case TOML_STRING: indent(depth); printf("\"%s\"\n", v->as.string); break;
case TOML_DATETIME: indent(depth); printf("%s\n", v->as.string); break;
case TOML_INTEGER: indent(depth); printf("%lld\n", v->as.integer); break;
case TOML_FLOAT: indent(depth); printf("%g\n", v->as.real); break;
case TOML_BOOL: indent(depth); printf("%s\n", v->as.boolean ? "true" : "false"); break;
case TOML_ARRAY:
indent(depth); printf("[\n");
for (size_t i = 0; i < v->as.array.count; i++) toml_dump(v->as.array.items[i], depth + 1);
indent(depth); printf("]\n");
break;
case TOML_TABLE:
for (TomlKeyVal* kv = v->as.table.head; kv; kv = kv->next) {
indent(depth); printf("%s = ", kv->key);
if (kv->value->kind == TOML_TABLE || kv->value->kind == TOML_ARRAY) { printf("\n"); toml_dump(kv->value, depth + 1); }
else toml_dump(kv->value, 0);
}
break;
}
}
+78
View File
@@ -0,0 +1,78 @@
/*
* TinyBlocks - tb_toml.c
* Library tinyblocks-toml: registra o bloco Toml.Get e helpers de metadados.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_toml.h"
#define CAT_COLOR 0.62f, 0.44f, 0.86f, 1.f
#define CAT_DARK 0.49f, 0.33f, 0.70f, 1.f
static const char* value_to_text(const TomlValue* v, char* buf, size_t cap) {
if (!v) { buf[0] = 0; return buf; }
switch (v->kind) {
case TOML_STRING:
case TOML_DATETIME: snprintf(buf, cap, "%s", v->as.string ? v->as.string : ""); break;
case TOML_INTEGER: snprintf(buf, cap, "%lld", v->as.integer); break;
case TOML_FLOAT: snprintf(buf, cap, "%g", v->as.real); break;
case TOML_BOOL: snprintf(buf, cap, "%s", v->as.boolean ? "true" : "false"); break;
default: buf[0] = 0; break;
}
return buf;
}
static void eval_toml_get(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value text = tb_block_get_input(self, rt, 0);
TinyBlocks_Value key = tb_block_get_input(self, rt, 1);
const char* src = (text.kind == TB_VALUE_TEXT && text.as.text) ? text.as.text : "";
const char* dotted = (key.kind == TB_VALUE_TEXT && key.as.text) ? key.as.text : "";
TomlLexError err;
TomlDoc* doc = toml_parse(src, &err);
char out[512] = "";
if (doc) {
const TomlValue* v = toml_path_get(doc->root, dotted);
value_to_text(v, out, sizeof(out));
toml_free(doc);
}
tb_block_set_output(self, 0, tb_value_text(out));
self->dirty = false;
}
static bool toml_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = { "TOML", {CAT_COLOR}, {CAT_DARK} };
tb_library_set_category(lib, &cat);
static const TinyBlocks_SlotDesc in[] = {{"texto", TB_VALUE_TEXT}, {"chave", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc out[] = {{"valor", TB_VALUE_TEXT}};
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Toml.Get", in, 2, out, 1, eval_toml_get);
return t && tb_library_add(lib, &t->base);
}
static void toml_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; }
TINYBLOCKS_DEFINE_LIBRARY(toml,
"tinyblocks-toml",
"1.0.0",
toml_init,
toml_deinit)
const TinyBlocks_LibraryDescriptor* tb_toml_get_library(void) {
return &_tb_lib_desc_toml;
}
const char* tb_toml_file_get(const char* path, const char* dotted, const char* def) {
static char buf[256];
TomlLexError err;
TomlDoc* doc = toml_parse_file(path, &err);
if (!doc) return def;
const TomlValue* v = toml_path_get(doc->root, dotted);
if (!v) { toml_free(doc); return def; }
value_to_text(v, buf, sizeof(buf));
toml_free(doc);
return buf;
}