1

I have written a program using Lex and Yacc.I want to know how to get the parser tree of that using this program.Can anyone please give me the code to get it? I have used gcc lex.yy.c y.tab.c -o project.exe

4

1 回答 1

3

Lex/Yacc 不会自己构建树,它们只会执行您的代码在某个规则匹配时这意味着它非常灵活,但也意味着由您来编写构建树的代码。

幸运的是,建造树木并不是很复杂。查看此链接以获取您可以使用的示例。诀窍是您可以使用 yacc 的语义值($$和朋友)来传递树节点:

input  : exp ';'               {do_something_with($1);}
       ;

exp    : '+' term              {$$ = $2;}
       | '-' term              {$$ = make_operator(NULL, '~', $2);}
       | term                  {$$ = $1;}
       | exp '+' term          {$$ = make_operator($1, '+', $3);}
       | exp '-' term          {$$ = make_operator($1, '-', $3);}
       ;

term   : factor                {$$ = $1;}
       | term '*' factor       {$$ = make_operator($1, '*', $3);}
       | term '/' factor       {$$ = make_operator($1, '/', $3);}
       ;

factor : number                {$$ = make_number($1);}
       | variable              {$$ = make_variable($1);}
       | '(' exp ')'           {$$ = $2;}
       ;

您显然会定义自己的函数来制作实际节点。再次,查看链接以获取示例。

于 2013-06-01T13:04:20.473 回答