Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the AST from YACC?

I know how to make YACC generate an AST, but how do you actaully get it? I mean, how do you actaully get the value of the root node from YACC?

like image 521
mtk358 Avatar asked Apr 12 '11 20:04

mtk358


3 Answers

Yacc only gives you back one node at a time, and it's always something that you just gave yacc at some earlier time, i.e., whatever you wanted to return from a reduced production or whatever you wanted to return from a terminal symbol. (Sorry, you said you knew that, but some people reading this might not.)

So, take whatever you woud have returned from the root or top rule, and save it (in your attached C reduction code) any way you like.

like image 139
DigitalRoss Avatar answered Oct 06 '22 15:10

DigitalRoss


What Yacc gives you is a parse tree, which is different than an AST. You'd need to construct your AST by yourselves while going through each node of the parse tree (through yacc).

like image 35
ryaner Avatar answered Oct 06 '22 14:10

ryaner


This is how I did it:

in the yacc file (your_grammar.y):

%parse-param {AstNode **pproot}
%parse-param {char **errmsg}

in the calling program (your_program.c):

res = yyparse(&pAst, &errmsg);

AST nodes are allocated and linked as a tree inside yyparse() (you make the logic) and the address of root node is passed back in the pAst pointer.

like image 32
jaeheung Avatar answered Oct 06 '22 16:10

jaeheung