#define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include "tinyblocks/tinyblocks.h" struct TinyBlocks_JsonValue { TinyBlocks_Object obj; /* contagem de referencias (1o campo) */ TinyBlocks_JsonKind kind; union { bool boolean; double number; char* string; struct { TinyBlocks_JsonValue** items; uint32_t count, capacity; } array; struct { char** keys; TinyBlocks_JsonValue** values; uint32_t count, capacity; } object; } as; }; /* === * Construtores / ciclo de vida * === */ static void json_destroy(TinyBlocks_JsonValue* j); static void json_object_destroy(TinyBlocks_Object* o) { json_destroy((TinyBlocks_JsonValue*)o); } static const TinyBlocks_ObjectClass s_json_class = { "JSON", json_object_destroy }; static TinyBlocks_JsonValue* json_alloc(TinyBlocks_JsonKind kind) { TinyBlocks_JsonValue* j = calloc(1, sizeof(TinyBlocks_JsonValue)); if (!j) return NULL; tb_object_init(&j->obj, &s_json_class); j->kind = kind; return j; } TinyBlocks_JsonValue* tb_json_null(void) { return json_alloc(TB_JSON_NULL); } TinyBlocks_JsonValue* tb_json_bool(bool b) { TinyBlocks_JsonValue* j = json_alloc(TB_JSON_BOOL); if (j) j->as.boolean = b; return j; } TinyBlocks_JsonValue* tb_json_number(double d) { TinyBlocks_JsonValue* j = json_alloc(TB_JSON_NUMBER); if (j) j->as.number = d; return j; } TinyBlocks_JsonValue* tb_json_string(const char* s) { TinyBlocks_JsonValue* j = json_alloc(TB_JSON_STRING); if (!j) return NULL; j->as.string = strdup(s ? s : ""); return j; } TinyBlocks_JsonValue* tb_json_array(void) { return json_alloc(TB_JSON_ARRAY); } TinyBlocks_JsonValue* tb_json_object(void) { return json_alloc(TB_JSON_OBJECT); } static void json_destroy(TinyBlocks_JsonValue* j) { switch (j->kind) { case TB_JSON_STRING: free(j->as.string); break; case TB_JSON_ARRAY: for (uint32_t i = 0; i < j->as.array.count; i++) tb_json_release(j->as.array.items[i]); free(j->as.array.items); break; case TB_JSON_OBJECT: for (uint32_t i = 0; i < j->as.object.count; i++) { free(j->as.object.keys[i]); tb_json_release(j->as.object.values[i]); } free(j->as.object.keys); free(j->as.object.values); break; default: break; } free(j); } void tb_json_retain(TinyBlocks_JsonValue* j) { tb_object_retain(j); } void tb_json_release(TinyBlocks_JsonValue* j) { tb_object_release(j); } TinyBlocks_JsonValue* tb_json_clone(const TinyBlocks_JsonValue* j) { if (!j) return NULL; switch (j->kind) { case TB_JSON_NULL: return tb_json_null(); case TB_JSON_BOOL: return tb_json_bool(j->as.boolean); case TB_JSON_NUMBER: return tb_json_number(j->as.number); case TB_JSON_STRING: return tb_json_string(j->as.string); case TB_JSON_ARRAY: { TinyBlocks_JsonValue* out = tb_json_array(); if (!out) return NULL; for (uint32_t i = 0; i < j->as.array.count; i++) { TinyBlocks_JsonValue* item = tb_json_clone(j->as.array.items[i]); tb_json_array_push(out, item); tb_json_release(item); } return out; } case TB_JSON_OBJECT: { TinyBlocks_JsonValue* out = tb_json_object(); if (!out) return NULL; for (uint32_t i = 0; i < j->as.object.count; i++) { TinyBlocks_JsonValue* val = tb_json_clone(j->as.object.values[i]); tb_json_object_set(out, j->as.object.keys[i], val); tb_json_release(val); } return out; } } return tb_json_null(); } /* === * Inspeção * === */ TinyBlocks_JsonKind tb_json_kind(const TinyBlocks_JsonValue* j) { return j ? j->kind : TB_JSON_NULL; } const char* tb_json_kind_name(const TinyBlocks_JsonValue* j) { switch (tb_json_kind(j)) { case TB_JSON_NULL: return "null"; case TB_JSON_BOOL: return "bool"; case TB_JSON_NUMBER: return "number"; case TB_JSON_STRING: return "string"; case TB_JSON_ARRAY: return "array"; case TB_JSON_OBJECT: return "object"; } return "null"; } bool tb_json_as_bool(const TinyBlocks_JsonValue* j, bool def) { if (!j) return def; if (j->kind == TB_JSON_BOOL) return j->as.boolean; if (j->kind == TB_JSON_NUMBER) return j->as.number != 0.0; return def; } double tb_json_as_number(const TinyBlocks_JsonValue* j, double def) { if (!j) return def; if (j->kind == TB_JSON_NUMBER) return j->as.number; if (j->kind == TB_JSON_BOOL) return j->as.boolean ? 1.0 : 0.0; return def; } const char* tb_json_as_string(const TinyBlocks_JsonValue* j) { if (!j || j->kind != TB_JSON_STRING) return NULL; return j->as.string; } /* === * Arrays * === */ bool tb_json_array_push(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) { if (!arr || arr->kind != TB_JSON_ARRAY || !item) return false; if (arr->as.array.count == arr->as.array.capacity) { uint32_t cap = arr->as.array.capacity ? arr->as.array.capacity * 2 : 8; TinyBlocks_JsonValue** items = realloc(arr->as.array.items, cap * sizeof(*items)); if (!items) return false; arr->as.array.items = items; arr->as.array.capacity = cap; } tb_json_retain(item); arr->as.array.items[arr->as.array.count++] = item; return true; } bool tb_json_array_set(TinyBlocks_JsonValue* arr, uint32_t idx, TinyBlocks_JsonValue* item) { if (!arr || arr->kind != TB_JSON_ARRAY || !item || idx >= arr->as.array.count) return false; tb_json_retain(item); /* antes de soltar: pode ser o mesmo */ tb_json_release(arr->as.array.items[idx]); arr->as.array.items[idx] = item; return true; } bool tb_json_array_insert(TinyBlocks_JsonValue* arr, uint32_t idx, TinyBlocks_JsonValue* item) { if (!arr || arr->kind != TB_JSON_ARRAY || !item || idx > arr->as.array.count) return false; if (!tb_json_array_push(arr, item)) return false; /* cresce e retem no fim */ TinyBlocks_JsonValue** it = arr->as.array.items; uint32_t n = arr->as.array.count; memmove(&it[idx + 1], &it[idx], (size_t)(n - 1 - idx) * sizeof(*it)); it[idx] = item; return true; } bool tb_json_array_remove(TinyBlocks_JsonValue* arr, uint32_t idx) { if (!arr || arr->kind != TB_JSON_ARRAY || idx >= arr->as.array.count) return false; TinyBlocks_JsonValue** it = arr->as.array.items; tb_json_release(it[idx]); memmove(&it[idx], &it[idx + 1], (size_t)(arr->as.array.count - idx - 1) * sizeof(*it)); arr->as.array.count--; return true; } void tb_json_array_clear(TinyBlocks_JsonValue* arr) { if (!arr || arr->kind != TB_JSON_ARRAY) return; for (uint32_t i = 0; i < arr->as.array.count; i++) tb_json_release(arr->as.array.items[i]); arr->as.array.count = 0; } uint32_t tb_json_array_length(const TinyBlocks_JsonValue* arr) { return (arr && arr->kind == TB_JSON_ARRAY) ? arr->as.array.count : 0; } TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_t idx) { if (!arr || arr->kind != TB_JSON_ARRAY || idx >= arr->as.array.count) return NULL; TinyBlocks_JsonValue* v = arr->as.array.items[idx]; tb_json_retain(v); return v; } /* === * Objetos * === */ bool tb_json_object_set(TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val) { if (!obj || obj->kind != TB_JSON_OBJECT || !key || !val) return false; for (uint32_t i = 0; i < obj->as.object.count; i++) { if (strcmp(obj->as.object.keys[i], key) == 0) { tb_json_release(obj->as.object.values[i]); tb_json_retain(val); obj->as.object.values[i] = val; return true; } } if (obj->as.object.count == obj->as.object.capacity) { uint32_t cap = obj->as.object.capacity ? obj->as.object.capacity * 2 : 8; char** keys = realloc(obj->as.object.keys, cap * sizeof(*keys)); TinyBlocks_JsonValue** values = realloc(obj->as.object.values, cap * sizeof(*values)); if (!keys || !values) { free(keys); free(values); return false; } obj->as.object.keys = keys; obj->as.object.values = values; obj->as.object.capacity = cap; } obj->as.object.keys[obj->as.object.count] = strdup(key); tb_json_retain(val); obj->as.object.values[obj->as.object.count] = val; obj->as.object.count++; return true; } uint32_t tb_json_object_length(const TinyBlocks_JsonValue* obj) { return (obj && obj->kind == TB_JSON_OBJECT) ? obj->as.object.count : 0; } const char* tb_json_object_key_at(const TinyBlocks_JsonValue* obj, uint32_t idx) { if (!obj || obj->kind != TB_JSON_OBJECT || idx >= obj->as.object.count) return NULL; return obj->as.object.keys[idx]; } TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key) { if (!obj || obj->kind != TB_JSON_OBJECT || !key) return NULL; for (uint32_t i = 0; i < obj->as.object.count; i++) { if (strcmp(obj->as.object.keys[i], key) == 0) { tb_json_retain(obj->as.object.values[i]); return obj->as.object.values[i]; } } return NULL; } /* === * Parser (recursive-descent, RFC 8259 simplificado) * === */ typedef struct { const char* p; const char* end; char* err; size_t errcap; } JsonParser; static void parser_fail(JsonParser* ps, const char* msg) { if (ps->err && ps->errcap) snprintf(ps->err, ps->errcap, "%s", msg); } static void skip_ws(JsonParser* ps) { while (ps->p < ps->end && isspace((unsigned char)*ps->p)) ps->p++; } static TinyBlocks_JsonValue* parse_value(JsonParser* ps); static bool parse_literal(JsonParser* ps, const char* lit) { size_t n = strlen(lit); if ((size_t)(ps->end - ps->p) < n) return false; if (memcmp(ps->p, lit, n) != 0) return false; ps->p += n; return true; } static char* parse_string_raw(JsonParser* ps) { if (ps->p >= ps->end || *ps->p != '"') { parser_fail(ps, "esperado '\"'"); return NULL; } ps->p++; size_t cap = 32, len = 0; char* buf = malloc(cap); if (!buf) return NULL; while (ps->p < ps->end && *ps->p != '"') { unsigned char c = (unsigned char)*ps->p++; char out = (char)c; if (c == '\\') { if (ps->p >= ps->end) { free(buf); parser_fail(ps, "string truncada"); return NULL; } char esc = *ps->p++; switch (esc) { case '"': out = '"'; break; case '\\': out = '\\'; break; case '/': out = '/'; break; case 'b': out = '\b'; break; case 'f': out = '\f'; break; case 'n': out = '\n'; break; case 'r': out = '\r'; break; case 't': out = '\t'; break; case 'u': { if (ps->end - ps->p < 4) { free(buf); parser_fail(ps, "\\u incompleto"); return NULL; } unsigned cp = 0; for (int i = 0; i < 4; i++) { char h = ps->p[i]; cp <<= 4; if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0'); else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10); else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10); else { free(buf); parser_fail(ps, "\\u inválido"); return NULL; } } ps->p += 4; /* codifica em UTF-8 (apenas BMP, sem pares substitutos) */ if (len + 4 >= cap) { cap *= 2; buf = realloc(buf, cap); if (!buf) return NULL; } if (cp < 0x80) { buf[len++] = (char)cp; } else if (cp < 0x800) { buf[len++] = (char)(0xC0 | (cp >> 6)); buf[len++] = (char)(0x80 | (cp & 0x3F)); } else { buf[len++] = (char)(0xE0 | (cp >> 12)); buf[len++] = (char)(0x80 | ((cp >> 6) & 0x3F)); buf[len++] = (char)(0x80 | (cp & 0x3F)); } continue; } default: free(buf); parser_fail(ps, "escape inválido"); return NULL; } } if (len + 1 >= cap) { cap *= 2; buf = realloc(buf, cap); if (!buf) return NULL; } buf[len++] = out; } if (ps->p >= ps->end) { free(buf); parser_fail(ps, "string não terminada"); return NULL; } ps->p++; /* fecha '"' */ buf[len] = '\0'; return buf; } static TinyBlocks_JsonValue* parse_number(JsonParser* ps) { const char* start = ps->p; if (ps->p < ps->end && *ps->p == '-') ps->p++; while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++; if (ps->p < ps->end && *ps->p == '.') { ps->p++; while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++; } if (ps->p < ps->end && (*ps->p == 'e' || *ps->p == 'E')) { ps->p++; if (ps->p < ps->end && (*ps->p == '+' || *ps->p == '-')) ps->p++; while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++; } if (ps->p == start) { parser_fail(ps, "número inválido"); return NULL; } char tmp[64]; size_t n = (size_t)(ps->p - start); if (n >= sizeof(tmp)) n = sizeof(tmp) - 1; memcpy(tmp, start, n); tmp[n] = '\0'; return tb_json_number(strtod(tmp, NULL)); } static TinyBlocks_JsonValue* parse_array(JsonParser* ps) { ps->p++; /* '[' */ TinyBlocks_JsonValue* arr = tb_json_array(); skip_ws(ps); if (ps->p < ps->end && *ps->p == ']') { ps->p++; return arr; } for (;;) { skip_ws(ps); TinyBlocks_JsonValue* item = parse_value(ps); if (!item) { tb_json_release(arr); return NULL; } tb_json_array_push(arr, item); tb_json_release(item); skip_ws(ps); if (ps->p < ps->end && *ps->p == ',') { ps->p++; continue; } if (ps->p < ps->end && *ps->p == ']') { ps->p++; break; } tb_json_release(arr); parser_fail(ps, "esperado ',' ou ']'"); return NULL; } return arr; } static TinyBlocks_JsonValue* parse_object(JsonParser* ps) { ps->p++; /* '{' */ TinyBlocks_JsonValue* obj = tb_json_object(); skip_ws(ps); if (ps->p < ps->end && *ps->p == '}') { ps->p++; return obj; } for (;;) { skip_ws(ps); char* key = parse_string_raw(ps); if (!key) { tb_json_release(obj); return NULL; } skip_ws(ps); if (ps->p >= ps->end || *ps->p != ':') { free(key); tb_json_release(obj); parser_fail(ps, "esperado ':'"); return NULL; } ps->p++; skip_ws(ps); TinyBlocks_JsonValue* val = parse_value(ps); if (!val) { free(key); tb_json_release(obj); return NULL; } tb_json_object_set(obj, key, val); free(key); tb_json_release(val); skip_ws(ps); if (ps->p < ps->end && *ps->p == ',') { ps->p++; continue; } if (ps->p < ps->end && *ps->p == '}') { ps->p++; break; } tb_json_release(obj); parser_fail(ps, "esperado ',' ou '}'"); return NULL; } return obj; } static TinyBlocks_JsonValue* parse_value(JsonParser* ps) { skip_ws(ps); if (ps->p >= ps->end) { parser_fail(ps, "fim inesperado"); return NULL; } char c = *ps->p; if (c == '{') return parse_object(ps); if (c == '[') return parse_array(ps); if (c == '"') { char* s = parse_string_raw(ps); if (!s) return NULL; TinyBlocks_JsonValue* j = tb_json_string(s); free(s); return j; } if (c == '-' || isdigit((unsigned char)c)) return parse_number(ps); if (parse_literal(ps, "true")) return tb_json_bool(true); if (parse_literal(ps, "false")) return tb_json_bool(false); if (parse_literal(ps, "null")) return tb_json_null(); parser_fail(ps, "token inesperado"); return NULL; } TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbuf_size) { if (!text) { if (errbuf && errbuf_size) snprintf(errbuf, errbuf_size, "texto nulo"); return NULL; } JsonParser ps = { .p = text, .end = text + strlen(text), .err = errbuf, .errcap = errbuf_size }; TinyBlocks_JsonValue* v = parse_value(&ps); if (!v) return NULL; skip_ws(&ps); if (ps.p != ps.end) { tb_json_release(v); if (errbuf && errbuf_size) snprintf(errbuf, errbuf_size, "lixo após valor JSON"); return NULL; } return v; } /* === * Stringify * === */ typedef struct { char* buf; size_t len, cap; } StrBuf; static void sb_ensure(StrBuf* sb, size_t extra) { if (sb->len + extra + 1 <= sb->cap) return; size_t cap = sb->cap ? sb->cap * 2 : 64; while (cap < sb->len + extra + 1) cap *= 2; sb->buf = realloc(sb->buf, cap); sb->cap = cap; } static void sb_append(StrBuf* sb, const char* s) { size_t n = strlen(s); sb_ensure(sb, n); memcpy(sb->buf + sb->len, s, n); sb->len += n; sb->buf[sb->len] = '\0'; } static void sb_append_quoted(StrBuf* sb, const char* s) { sb_append(sb, "\""); for (const unsigned char* p = (const unsigned char*)s; *p; p++) { char tmp[8]; switch (*p) { case '"': sb_append(sb, "\\\""); break; case '\\': sb_append(sb, "\\\\"); break; case '\n': sb_append(sb, "\\n"); break; case '\r': sb_append(sb, "\\r"); break; case '\t': sb_append(sb, "\\t"); break; default: if (*p < 0x20) { snprintf(tmp, sizeof(tmp), "\\u%04x", *p); sb_append(sb, tmp); } else { tmp[0] = (char)*p; tmp[1] = '\0'; sb_append(sb, tmp); } } } sb_append(sb, "\""); } static void stringify_rec(StrBuf* sb, const TinyBlocks_JsonValue* j) { if (!j) { sb_append(sb, "null"); return; } char tmp[64]; switch (j->kind) { case TB_JSON_NULL: sb_append(sb, "null"); break; case TB_JSON_BOOL: sb_append(sb, j->as.boolean ? "true" : "false"); break; case TB_JSON_NUMBER: if (isfinite(j->as.number) && j->as.number == (double)(int64_t)j->as.number) snprintf(tmp, sizeof(tmp), "%lld", (long long)j->as.number); else snprintf(tmp, sizeof(tmp), "%g", j->as.number); sb_append(sb, tmp); break; case TB_JSON_STRING: sb_append_quoted(sb, j->as.string); break; case TB_JSON_ARRAY: sb_append(sb, "["); for (uint32_t i = 0; i < j->as.array.count; i++) { if (i) sb_append(sb, ","); stringify_rec(sb, j->as.array.items[i]); } sb_append(sb, "]"); break; case TB_JSON_OBJECT: sb_append(sb, "{"); for (uint32_t i = 0; i < j->as.object.count; i++) { if (i) sb_append(sb, ","); sb_append_quoted(sb, j->as.object.keys[i]); sb_append(sb, ":"); stringify_rec(sb, j->as.object.values[i]); } sb_append(sb, "}"); break; } } char* tb_json_stringify(const TinyBlocks_JsonValue* j) { StrBuf sb = {0}; stringify_rec(&sb, j); if (!sb.buf) sb.buf = strdup("null"); return sb.buf; } /* === * Helpers para TinyBlocks_Value * === */ TinyBlocks_Value tb_value_json(TinyBlocks_JsonValue* j) { TinyBlocks_Value v = { .kind = TB_VALUE_JSON, .as.json = j }; if (j) tb_json_retain(j); return v; } TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v) { return v.kind == TB_VALUE_JSON ? v.as.json : NULL; }