Hosneara Ahmed
Hosneara Ahmed

Reputation: 41

Inherited attributes in bison/yacc

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

Answers (2)

rici
rici

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

Chris Dodd
Chris Dodd

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

Related Questions