Building AST Using Bison

I am working with Bison to build an AST for the compiler I am writing. What is the best way to create nodes in an AST? My question may be clearer with an example.

Given the following snippet:

field : modifier type TOK_IDENT TOK_SEMICOLON { // I want to return a pointer to a node of type Field // ie $$ = new Field(name, isVisible, isStatic, type); } ; modifier : visibility_opt static_opt { // Should I make the new Field here and pass it up? // Or a new type that contains both vis and static options? } ; visibility_opt : /* default */ { $$ = true; } | TOK_PUBLIC { $$ = true; } | TOK_PRIVATE { $$ = false; } ; static_opt : /* default */ { $$ = false; } | TOK_STATIC { $$ = true; } ; 

In the above example, I want the field rule to return the node field, but I need some attributes of the modifier rule that will be passed during parsing (i.e. these are synthesized attributes).

I can imagine two ways to do this without changing the grammar.

  • Make a modifier that does not contain a term, enter the field type, create a new field here, fill in everything that I can, and pass it to the field to fill in the rest.
  • Let the modifier have its own type, which contains two bool values ​​and passes this data extraction when creating a new field in the field rule.

In situations like this, what is the preferred way?

+4
source share
1 answer

Like others, he suggested that the preferred method would be to have a structure modifier with visibility and static parameters. But I will probably make it a static modifier in the sense that it will not be passed to the field, but instead is simply used to retrieve the values, and then passed to the field. You can even push it onto the stack and reuse it to make it faster.

Something in the following lines:

 static struct { boolean vis_opt; boolean static_opt; } mod; field : modifier type TOK_IDENT TOK_SEMICOLON { $$ = new Field(..., mod.vis_opt, mod.static_opt, ...); } ; modifier : visibility_opt static_opt { mod.vis_opt = $1; mod.static_opt = $2; } ; visibility_opt : /* default */ { $$ = true; } | TOK_PUBLIC { $$ = true; } | TOK_PRIVATE { $$ = false; } ; static_opt : /* default */ { $$ = false; } | TOK_STATIC { $$ = true; } ; 

In addition, if you are not sure about the future of the language, you may want to make visibility an enumeration. You never know what kind of visibility it is, you can dream when developing a language, and at least if you have it in the enumeration, it is easier to extend it later.

Enjoy.

+2
source

Source: https://habr.com/ru/post/1403246/


All Articles