Porting cJSON to Moxy
Moxy's pitch is that a C file renamed to .mxy compiles, that moxy fix modernizes the mechanical parts, and that rewriting the rest removes the busywork of strings, collections, errors and memory. This page tests that on cJSON, a widely used JSON library: one 3,206-line C file plus its header. The port, its scripts and its benchmark are in examples/cjson.
Source: cJSON 1.7.19, commit 6d9f2443ab071f86e5d9b43025a40929ec41c46c (2026-09-16), MIT licensed. Its notice is kept in examples/cjson/LICENSE and named in every ported file.
The short version:
- The unchanged file compiles and passes cJSON's whole test suite, but only after four compiler fixes this port forced. Two of them were silent miscompilations of valid C.
moxy fixchanged nothing. cJSON's cleanup code runs only on failure, whichdefercan't express.- The hand port removes every line of manual memory management and error cleanup from the parser and printer, and about half their lines. It passes all of cJSON's tests that use the public API, and matches cJSON byte for byte on 100,000 generated inputs.
- It parses about 1.3x slower than cJSON. Printing is level, because both spend their time in the same C calls. cJSON's C API on top of the port costs 1.25x or more overall and 1.5x the memory, and that layer is still C.
Step 1: compile it unchanged
cp cJSON.c cjson.mxy, then moxy emit cjson.mxy, then run all 21 of cJSON's unit test files against the generated C (they #include "../cJSON.c"; unchanged.sh points that at the generated file).
With Moxy as it was before this port, the file did not compile. In order:
| Problem | Kind | Fix |
|---|---|---|
CJSON_PUBLIC(cJSON *) cJSON_Parse(...): a macro from cJSON.h wrapping the return type |
parse error | the parser keeps MACRO(type) before a top-level function and writes it back in the generated C |
const cJSON * const item where cJSON is a typedef only the header declares |
parse error | a name after const or volatile followed by * or a name is a type |
void * CJSON_CDECL internal_malloc(size_t): a calling-convention macro before the name |
parse error | kept before the name in the generated C; inside a function pointer declarator it's dropped (x86-64 and ARM64, Moxy's only targets, ignore conventions) |
printbuffer buffer[1]; buffer->length = ...: -> on a one-element array |
type error | -> on an array of structs reads its first element, as in C |
strlen(value) + sizeof("") |
silent miscompilation | Moxy turned the literal into a string pointer, so sizeof was 8 instead of 1. cJSON's tests caught it: error positions off, 5 failures. sizeof on a string literal is now the array's size |
cJSON_ArrayForEach(element, array) { ... }, a macro expanding to a for header |
silent miscompilation | Moxy's optional semicolons read it as a call statement followed by a block, so the loop body ran once with element NULL. cJSON's tests crashed in cJSON_Compare. A call to a name that isn't a Moxy function, directly followed by a block, is now compiled as a loop with that header |
After the fixes, cjson.mxy is byte for byte cJSON.c, and cJSON's tests against the generated C give 162 passed, 1 ignored (as upstream), 0 failed. The generated C runs at cJSON's speed (table below). It still prints 8 warnings, one per cJSON type constant: cJSON_String is two edits from cJSON_IsString, so Moxy suggests a typo. This port made that warning appear once per name instead of at every use (it was 52).
The two miscompilations are the important finding. Moxy's promise is that valid C keeps its meaning; both were valid C that silently changed meaning, and only a real test suite found them. Each fix has a test in tests/interop/libapi.mxy.
Step 2: moxy fix
moxy fix cjson.mxy rewrote nothing and printed 9 suggestions:
- 7 ×
'goto fail' could become 'defer', but this return leaves without running the code after 'fail'(and 2 of those functions have two labels). cJSON's pattern is: build something,returnit on success, and on any errorgoto fail, which frees the half-built result. That cleanup must run only on failure.deferruns on every exit, so the rewrite would free the result on success too. Moxy has noerrdefer; withResultand managed values the cleanup simply disappears (step 3), but that is a rewrite, not a fix. goto loop_endinparse_number: agotoused as abreakout of aswitchinside a loop.versionis astatic char[15]filled bysprintf;moxy fixwon't turn a static buffer into astring.
None of moxy fix's other patterns (realloc-grown arrays, char buffers filled with strcpy, printf with \n) occur in cJSON in a form it can prove equivalent: cJSON grows its print buffer through a hooks struct, not realloc directly.
Step 3: by hand
cJSON's data structure is its API: a cJSON node with next, prev, child, type, valuestring, valueint, valuedouble and string, which callers walk, rewire and free with cJSON_Delete. A Moxy value can't be handed to C code that frees it, so the port is two layers:
json/, the Moxy library.enum Json { Null, Bool(bool), Number(double), String(string), Array(Json[]), Object(Member[]), Raw(string) }, whereMemberis a key and a value; objects keep order and duplicate keys, as cJSON does.Json::parse(text)returnsResult<Json, JsonError>, and the error carries the byte offset cJSON reports for the same text. Printing goes through theFormatinterface into Moxy'sBuf, which replaces cJSON's hand-grown print buffer. Nomalloc,free,goto failorcJSON_Deleteanywhere: a parse that fails half-way leaves nothing to free.capi/, cJSON's C API in C-style Moxy: the samestruct cJSONlayout, everycJSON_*function incJSON.h(78), thecJSON_Hooksallocator,cJSON_GetErrorPtr. Tree functions (create, add, detach, replace, duplicate, delete) are cJSON's logic, rewritten more compactly. Parsing, printing, minifying and comparing calljson/:cJSON_Parseparses into aJsonand builds nodes from it;cJSON_Printreads the nodes into aJsonand prints that.
The port reproduces cJSON's behaviour, quirks included, rather than fixing it: whitespace is every byte up to 32, invalid \u hex digits read as 0, cJSON_Minify drops a lone / and only knows the \" escape, a number is the longest run of 0-9+-eE. read by strtod, and a float prints as %1.15g, or %1.17g when that doesn't read back.
Lines of code
Counted by examples/cjson/count.ts. "Code" is lines left after removing comments and blank lines; "without braces" also drops lines holding only { or }, since cJSON gives every brace its own line and the port doesn't. "Allocates" and "frees" are code lines calling an allocator (malloc, realloc, the hooks, cJSON_strdup, cJSON_New_Item, cJSON's ensure, the port's copy_* and new_item) or a release (free, the hooks, cJSON_free, cJSON_Delete); "goto fail" counts the jumps and labels. cJSON.c's "core" is the functions json/ replaces; its "api" is the rest.
| code | code without braces | allocates | frees | goto fail | |
|---|---|---|---|---|---|
| cJSON.c, core (parse, print, minify, compare) | 1239 | 807 | 25 | 11 | 35 |
| json/ (Moxy) | 540 | 430 | 0 | 0 | 0 |
| cJSON.c, api (nodes, tree, create) | 1288 | 786 | 31 | 33 | 12 |
| capi/ (Moxy, C-style) | 655 | 538 | 23 | 19 | 0 |
| cJSON.c, total | 2527 | 1593 | 56 | 44 | 47 |
| port, total | 1195 | 968 | 23 | 19 | 0 |
The core lost all 71 lines of memory management and cleanup jumps and 47% of its lines without braces. The C API kept 42 of its 76 such lines, because it really does manage memory for its callers. Its lower line count comes from denser formatting and shared helpers (one array_of taking a closure replaces cJSON's four copies of the array builders), not from managed memory.
Correctness
- cJSON's tests against
capi/(check.sh): 108 of 108 pass, from the 10 test files that use only the public API, including the three cJSON_Utils suites with the originalcJSON_Utils.clinked against the port.compat/common.hreplaces the tests'common.h(which includescJSON.c), adds the headers andtrue/falsethat cJSON.c used to provide, and gives two static helpers the tests call public-API bodies (compare_double, andadd_item_to_arrayascJSON_AddItemToArray). The same 108 pass under AddressSanitizer and UndefinedBehaviorSanitizer. - Not run: 55 of cJSON's 163 tests. 51, in 11 files (
parse_number.c,print_string.c, ...), test cJSON.c's static functions directly, and 4 inmisc_tests.cdo the same (ensure,skip_utf8_bomtwice,cJSON_strdupwithglobal_hooks);check.shcuts those 4 out of the file. They can't link against any other implementation of the library. - Differential check (
differ/run.sh): 100,000 generated inputs, valid, broken and random, through cJSON and through the port's C API. The outputs are byte-identical: parse result,return_parse_endandcJSON_GetErrorPtroffsets, compact and formatted prints,cJSON_Compareagainst acJSON_Duplicate, andcJSON_Minify. - The Moxy API has tests in
tests/cjson/(parsing and printing, error offsets checked against cJSON's, comparison, minify).
Speed and memory
examples/cjson/bench/run.ts: a generated 6.2 MB formatted document of 20,000 records (nested objects, arrays of floats, strings with escapes and non-ASCII text), parsed and printed compact 10 times per run, median of 3 runs after a warm-up. All four programs print the same bytes. Apple M1 Max, macOS 27.2.1, Apple clang 21, cJSON at cc -O2, Moxy at moxy build --release (also cc -O2). The machine was shared with other builds (load average 8 to 10); differences under about 10% are noise.
| total | vs cJSON | parse | free | peak memory | ||
|---|---|---|---|---|---|---|
| cJSON 1.7.19, cc -O2 | 1269 ms | 1.00x | 212 ms | 984 ms | 67 ms | 79.8 MB |
| Moxy port, Moxy API (--release) | 1277 ms | 1.01x | 272 ms | 942 ms | 50 ms | 77.7 MB |
| Moxy port, cJSON C API | 1592 ms | 1.25x | 409 ms | 1109 ms | 67 ms | 119.2 MB |
| cJSON.c compiled by moxy (step 1) | 1268 ms | 1.00x | 211 ms | 982 ms | 67 ms | 79.8 MB |
Two more runs of the script on the same loaded machine gave, against cJSON: Moxy API 1.03x and 1.04x (parse 1.31x and 1.33x), C API 1.25x and 1.63x, step 1 1.09x and 1.14x. Step 1 is cJSON's own code through cc -O2, so its spread is a fair measure of the noise: about 10%. Rerun on a quiet machine before quoting a figure.
Build cost: moxy emit of the port takes under 10 ms, but the generated C carries Moxy's runtime, so cc -O2 takes 0.36 s against 0.16 s for cJSON.c, and the object file is 71 KB against 28 KB. The benchmark binaries are 148 KB (Moxy API) and 94 KB (C API) against 73 KB.
Where Moxy was worse
- Parsing is about 1.3x slower (1.28x to 1.33x over three runs). Every value is a
Resultcopied up through each level, every list append retains the value and the temporary is released (with atomic reference counts, which Phase 2 M2 targets), and lists grow by reallocation where cJSON links one allocated node per value. Bounds checks are not the cost: replacing the checked byte reads with raw pointer reads changed parse time by under 1%. - The C API is a second copy of the work.
cJSON_Parsethrough the port parses into aJson, then builds cJSON nodes from it: 1.9x cJSON's parse time, and peak memory 1.5x, since both trees exist at once. Printing converts nodes back to aJsonfirst (1.13x). A port that wanted cJSON's API at cJSON's speed would parse straight into nodes, which is C, not Moxy. - The C API layer is C. 655 lines, 42 of them allocating or freeing. Moxy can't manage memory that C callers own and free with
cJSON_Delete; incremental adoption here means the Moxy part sits behind a C boundary that is as manual as before. - Build size and time. Each emitted file embeds the runtime: 2.5x the object size and 2.2x the C compile time of cJSON.c.
moxy fixhad nothing to offer for the most common cleanup pattern in C libraries (cleanup on failure only). Anerrdefer-style statement, or amoxy fixrule that recognizes "free the result, return NULL" blocks, would be needed.- Rough edges hit while writing the port:
- A
matchcan't be the expression of anothermatcharm on one line (Null => match other { ... },is a parse error); the arms needed blocks. Buf(the formatting buffer) is only a type insideimplblocks, so printing helpers had to be static methods of a struct.- There is no direct way to build a string from bytes; a one-byte string is
string((char)b), and UTF-8 encoding concatenates those. strtodneeds aconst char *cursor into the text:(const char *)self.src + self.pos, andafter - (const char *)digits(astringminus a pointer is an error).moxy fmtwritesvoid (*free_fn)(void *)asvoid(*free_fn)(void *), and the formatted port carries that spelling.- Cross-compiling the C API with MinGW gcc
-Wallgives one-Wstringop-overflowfalse positive inside the runtime'smxy_buf_put.
- A
Reproducing
git clone https://github.com/DaveGamble/cJSON /tmp/cjson # 6d9f244 was used here
make
CJSON=/tmp/cjson MOXY=./build/moxy sh examples/cjson/unchanged.sh # steps 1 and 2
CJSON=/tmp/cjson MOXY=./build/moxy sh examples/cjson/check.sh # cJSON's tests against capi/
CJSON=/tmp/cjson MOXY=./build/moxy sh examples/cjson/differ/run.sh # differential check
CJSON=/tmp/cjson bun examples/cjson/count.ts # line counts
CJSON=/tmp/cjson bun examples/cjson/bench/run.ts # speed and memory
./build/moxy test tests/cjson # the Moxy API