2

I'd like to define a schema in JSON and generate C files to encode/decode streams that conform to the schema. A simplified example...

The JSON object...

var schema = {
   version: 1,

   objectA: {
      key: 0,
      type: "uint32_t",
      defaultValue: 42
   },

   objectB: {
      key: 1,
      type: "int16_t",
      defaultValue: -128
   },

   objectC: {
      key: 2,
      type: "double"
      defaultValue: "3.1415926"
   }
};

...would result in a C header file...

#define SCHEMA_VERSION (1)

typedef enum keys
{
   key_objectA = 0,
   key_objectB = 1,
   key_objectC = 2,
   KEY_COUNT
} keys_t;

typedef uint32_t objectA_t;
typedef int16_t objectB_t;
typedef double objectC_t;

typedef union univ_value
{
   objectA_t objectA;
   objectB_t objectB;
   objectC_t objectC;
} value_t;

result_t encode(char * ostream, keys_t key, value_t * value);
result_t decode(char * istream, keys_t key, value_t * value);

...and a corresponding C source file (would contain the default values as an array, ommitted for brevity).

Is there a code generation library (ideally in Javascript) that I could use the generate the header and source file contents?

To be clear, I'm not looking to feed in the JSON directly; rather, ideally, the ability to do something (in Javascript) like:

var headerOutput;

headerOutput += dreamCGenerator.appendMacro("define", {
                    symbol: "SCHEMA_VERSION",
                    value: schema.version
                });

headerOutput += dreamCGenerator.appendEnum(...);

// etc...
mtbkrdave
  • 2,900
  • 3
  • 23
  • 24
  • There may be one, but its unlikely. This looks like a very particular format you've settled on, and this isn't a very common operation. Is this format defined somewhere? If so, please elaborate. If not, your best bet is to generate the source file on the server side, using a hand written generator. – nmio Aug 21 '15 at 04:05
  • The format here is just a strawman / simplified example; ultimately what I'm looking for is the generic code generation capability elaborated at the bottom of the question... – mtbkrdave Aug 21 '15 at 04:12
  • So you're looking for a C code generator in javascript rather than a js-to-c compiler? – slebetman Aug 21 '15 at 04:13

2 Answers2

1

After more research/reading, I'm leaning toward using a template engine like handlebars to generate the C header/source files. This seems to be the best approach to keep the C syntax out of Javascript-land...

mtbkrdave
  • 2,900
  • 3
  • 23
  • 24
0

Wouldn't you rather use protobuf:

https://developers.google.com/protocol-buffers/

Your schema will be very JSON like, and you can generate code for many languages. Also allows for optional fields and required fields.

bluesmoon
  • 3,918
  • 3
  • 25
  • 30