I want to implement a new language, and I would like to do it in C, with the famous flex+yacc combination. Well, the thing is, writing the whole AST code is very time consuming. Is there a tool that automatically generate the constructors for the structs?
I would like something with the following behavior:
input:
enum AgentKind {A_KIND1, A_KIND2};
typedef struct Agent_st
{
enum AgentKind kind;
union {
struct {int a, b, c} k1;
struct {int a, GList* rest} k2;
} u;
} Agent;
output:
Agent* agent_A_KIND1_new(int a, b, c)
{
Agent* a = (Agent*)malloc(sizeof(Agent));
a->kind = A_KIND1;
a->k1.a = a;
...
...
return a;
}
Agent* agent_A_KIND2_new(int a, GList* rest)
{ ... }
Thank you!
Well, since there was no tool I decided to code something this afternoon.
I started something that looks like a nice project, and I would like to continue it.
I coded a somewhat simple (just a bunch of nested folds inside the IO monad) code generator in Haskell, based in builtin haskell types.
The AST type declaration:
http://pastebin.com/gF9xF1vf
The C code generator, based on the AST declaration:
http://pastebin.com/83Z4GH38
And the generated result:
http://pastebin.com/jJPgm5PE
How can somebody not love Haskell?
🙂
ps: I coded this because the project I’m currently working on is going to suffer a huge amount of changes in the near future, and those changes will invalidade the AST, thus forcing me to code another AST module…
Now I can do it quite fast!
Thanks for the answer though.