Commit 2e40ef97
2e40ef97c00eMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
JSON.generate / JSON.dump of a Struct
A Struct now serializes to a JSON object of its members instead of being rejected as an unsupported user object. Each member is emitted by its type (int/float/bool/string with JSON escaping, poly via sp_json_val), with the nil sentinels rendered as null.
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 2e40ef97c00e
- Parent
- a7befaffb3ec
src/codegen.cmodifiedView file
@@ -1817,10 +1817,36 @@
18171817
/* JSON.generate(x) / JSON.dump(x) -> serialize a boxed value */18181818
if (recv >= 0 && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "ConstantReadNode") &&18191819
nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "JSON") &&1820-
(!strcmp(name, "generate") || !strcmp(name, "dump")) && argc == 1 &&1821-
!ty_is_object(comp_ntype(c, argv[0]))) { /* user objects have no JSON serializer yet */1822-
buf_puts(b, "sp_json_val("); emit_boxed(c, argv[0], b); buf_puts(b, ")");1823-
return;1820+
(!strcmp(name, "generate") || !strcmp(name, "dump")) && argc == 1) {1821+
TyKind at = comp_ntype(c, argv[0]);1822+
/* a Struct serializes as a JSON object of its members */1823+
if (ty_is_object(at) && c->classes[ty_object_class(at)].is_struct) {1824+
ClassInfo *cls = &c->classes[ty_object_class(at)];1825+
int ts = ++g_tmp;1826+
buf_printf(b, "({ sp_%s *_t%d = ", cls->name, ts); emit_expr(c, argv[0], b); buf_puts(b, "; sp_sprintf(\"{");1827+
for (int a = 0; a < cls->nivars; a++) {1828+
if (a) buf_puts(b, ",");1829+
buf_printf(b, "\\\"%s\\\":%%s", cls->ivars[a] + 1); /* member name, sans @ */1830+
}1831+
buf_puts(b, "}\"");1832+
for (int a = 0; a < cls->nivars; a++) {1833+
TyKind mt = cls->ivar_types[a];1834+
const char *iv = cls->ivars[a] + 1; /* field name, sans @ */1835+
buf_puts(b, ", ");1836+
if (mt == TY_INT) buf_printf(b, "(_t%d->iv_%s == SP_INT_NIL ? SPL(\"null\") : sp_int_to_s(_t%d->iv_%s))", ts, iv, ts, iv);1837+
else if (mt == TY_STRING) buf_printf(b, "(_t%d->iv_%s ? sp_json_str(_t%d->iv_%s) : SPL(\"null\"))", ts, iv, ts, iv);1838+
else if (mt == TY_FLOAT) buf_printf(b, "sp_float_to_s(_t%d->iv_%s)", ts, iv);1839+
else if (mt == TY_BOOL) buf_printf(b, "(_t%d->iv_%s ? SPL(\"true\") : SPL(\"false\"))", ts, iv);1840+
else if (mt == TY_POLY) buf_printf(b, "sp_json_val(_t%d->iv_%s)", ts, iv);1841+
else buf_puts(b, "SPL(\"null\")");1842+
}1843+
buf_printf(b, "); })");1844+
return;1845+
}1846+
if (!ty_is_object(at)) { /* other user objects have no JSON serializer yet */1847+
buf_puts(b, "sp_json_val("); emit_boxed(c, argv[0], b); buf_puts(b, ")");1848+
return;1849+
}18241850
}18251851
18261852
/* Dir.exist? / Dir.exists? -> directory test */