From 9153fc39c4f918f5004816b8cd8db017aedd54bd Mon Sep 17 00:00:00 2001 From: Jason Heeris Date: Fri, 1 Jan 2021 21:26:02 +0800 Subject: [PATCH] Add an annotation to typedef structs and enums. A new annotation 'typedefto' allows you to make a typedef in the generated code for structs and enums (but not union 'which' enums). --- compiler/c.capnp | 3 +++ compiler/capnpc-c.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/compiler/c.capnp b/compiler/c.capnp index 2af08b9..92c955a 100644 --- a/compiler/c.capnp +++ b/compiler/c.capnp @@ -43,3 +43,6 @@ annotation fieldgetset @0xf72bc690355d66de (file): Void; annotation donotinclude @0x8c99797357b357e9 (file): UInt64; # do not generate an include directive for an import statement for the file with # the given ID + +annotation typedefto @0xcefaf27713042144 (struct, enum): Text; +# generate a typedef for the annotated struct or enum declaration diff --git a/compiler/capnpc-c.c b/compiler/capnpc-c.c index f21e913..2512f13 100644 --- a/compiler/capnpc-c.c +++ b/compiler/capnpc-c.c @@ -191,6 +191,24 @@ static void define_enum(struct node *n) { str_addf(&HDR, "\n\t%s_%s = %d", n->name.str, e.name.str, i); } str_addf(&HDR, "\n};\n"); + + for (i = capn_len(n->n.annotations)-1; i >= 0; i--) { + struct Annotation a; + struct Value v; + get_Annotation(&a, n->n.annotations, i); + read_Value(&v, a.value); + + switch (a.id) { + case 0xcefaf27713042144UL: + if (v.which != Value_text) { + fprintf(stderr, "schema breakage on $C::typedefto annotation\n"); + exit(2); + } + + str_addf(&HDR, "\ntypedef enum %s %s;\n", n->name.str, v.text.str); + break; + } + } } static void decode_value(struct value* v, Type_ptr type, Value_ptr value, const char *symbol) { @@ -1007,6 +1025,7 @@ static void define_group(struct strings *s, struct node *n, const char *group_na static void define_struct(struct node *n) { static struct strings s; + int i; str_reset(&s.dtab); str_reset(&s.ftab); @@ -1034,6 +1053,24 @@ static void define_struct(struct node *n) { str_add(&HDR, s.decl.str, s.decl.len); str_addf(&HDR, "};\n"); + for (i = capn_len(n->n.annotations)-1; i >= 0; i--) { + struct Annotation a; + struct Value v; + get_Annotation(&a, n->n.annotations, i); + read_Value(&v, a.value); + + switch (a.id) { + case 0xcefaf27713042144UL: + if (v.which != Value_text) { + fprintf(stderr, "schema breakage on $C::typedefto annotation\n"); + exit(2); + } + + str_addf(&HDR, "\ntypedef struct %s %s;\n", n->name.str, v.text.str); + break; + } + } + str_addf(&SRC, "\n%s_ptr new_%s(struct capn_segment *s) {\n", n->name.str, n->name.str); str_addf(&SRC, "\t%s_ptr p;\n", n->name.str); str_addf(&SRC, "\tp.p = capn_new_struct(s, %d, %d);\n", 8*n->n._struct.dataWordCount, n->n._struct.pointerCount);