dvidelabs / flatcc

FlatBuffers Compiler and Library in C for C
Apache License 2.0
632 stars 180 forks source link

Question on attribute implementation #192

Closed Dweller closed 3 years ago

Dweller commented 3 years ago

I've scratching my head over the attribute implemention. I can see flatcc parses and stores the defined attributes but apart from via the reflector I don't see any way of accessing them from within the builder or the printer.

I guess i could use the reflector to use the fbs schema to generate a API which will allow to to check but that seems like a lot of work.. Equally I guess I could use the XSD schema file I use to create the fbs file I'm using.

I just want to add a boolean flag to each table field so I can output the FlatBuffers data to XML...

Is there a more elegant way of implementing this I've missed?

mikkelfj commented 3 years ago

The attribute system is not very elegant in the FlatCC currently. FlatCC extracs the flags it needs as known flags and just leaves the rest in the parser graph (AST) where the reflection system is pulling them out as the only use case.

One reason is that semantics were a bit unclear - how do you handle duplicate attribute values? This has recently been settled: duplicates should not be allowed although FlatCC does not yet enforce this. This means that the attributes could be stored in a map. So far the only we to get to them is to traverse the AST graph along the attribute list path. And perhaps this is good enough in praxis, also going forward.

For your purpose I would write a small function (pseudocode) struct token *get_attribute(ASTNode *p, char *key) where token is start and length of an attribute value. It might be null if missing, or empty if the attribute has no value, or a string. I would simply perform a linear scan with strncmp to find a match. The function could be move to one of common support functions, but that would only make sense if there was code in the official repo that uses it.

You are welcome to propose an implementation and I can review it for you.

Note, this is all from memory, and just a quick answer to get you started.

mikkelfj commented 3 years ago

You may want to look at how attributes are exported for inspiration on how to implement the suggested function:

https://github.com/dvidelabs/flatcc/blob/c2158f1f1e6af8f313ee45ae394f51839c1715ba/src/compiler/codegen_schema.c#L146

Dweller commented 3 years ago

Thanks for that.. I'm not sure what the 'path of least resistance' is on this one.. If I an make it usefully reusable I'll certainly let you have a look. I suspect I'l be looking first at adding it my rehashed codegen_c_xml_printer() if I can access the attribute's there that sounds good at this stage. Time will tell I'm sure.. ;-)

mikkelfj commented 3 years ago

You should be able to do that. Feel free to reopen if you have anything to add.