Reputation: 41
How can I use inherited attributes in bison/yacc ?
Say, I have a grammar like this -
program -> stmts
What I wanted to do is in bison :
program : stmts {$$.next = newLabel(); $1.next = $$.next; }
Here next is an attribute declared in a structure and that type is added to union.
Upvotes: 3
Views: 1885
Reputation: 241791
You can sometimes use mid-rule actions to simulate top-down traverse during bottom-up parsing, but by far the cleanest and most flexible approach is to fill in attributes in the AST after the initial parse, using whatever combination of tree walks seem necessary.
Upvotes: 5
Reputation: 126243
In btyacc you can use:
program: stmts(newLabel()) { $$.next = $1.next; }
stmts($arg) : .... { $$.next = $arg; ... }
to do this sort of thing. This is equivalent to
program: { $<tag>$ = newLabel()); } stmts { $$.next = $1.next; }
stmts: .... { $$.next = $<tag>0; ... }
in bison (or yacc), but more type-safe. You'll need the right %union
and %type
declarations in either case.
Upvotes: 0