Show all entries

Sat 2023-01-28

Compiling key-value pairs into C code

I wrote some code that “compiles” a list of key-value pairs into C code. The keys and values must be strings, and I don’t yet do anything to detect special characters which must be escaped, or multi-line strings.

Here’s a test suite that tries a few different lists:


Here’s the reference output for that:


Here’s the Fexl code which does the actual code generation work:


The Fexl function compile_pairs generates a C function called "lookup". The lookup function takes a pointer to the key chars and a separate length. If you have NUL terminated data you can call strlen before calling lookup.

As far as I can tell the generated code is “optimal” in the sense that it does the fewest number of individual character comparisons needed to reach a point at which strncmp yields a definitive answer.

By the way, I could probably use “switch” instead of successive comparisons of the same key character, but I figure the optimizer will already have that covered.