Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Flex/Bison action result

I am using Flex/Bison/C++ to evaluate an expression Here is a sample bison file

string res; 
yy_scan_string(expression.c_str());               

yyparse();
cout<<"Result:"<<res<<"\n";
....
expr: expr PLUS expr { 
          $$=evaluate("+",$1,$3);
          res=$$;
          } 
     |expr MINUS expr { 
          $$=evaluate("-",$1,$3);
          res=$$;
          } 

Instead of using a variable res and storing the value in each action, is there a standard(like yylval) way to access the final result after yyparse()?

like image 361
yodhevauhe Avatar asked Dec 24 '10 16:12

yodhevauhe


People also ask

What does $$ mean in bison?

The sum is stored into $$ so that it becomes the semantic value of the addition-expression just recognized by the rule. If there were a useful semantic value associated with the `+' token, it could be referred to as $2 . If you don't specify an action for a rule, Bison supplies a default: $$ = $1 .

What is $1 in Bison?

The conversion value for 1 USD to 42.529 BISON.

How does flex bison work?

Bison produces parser from the input file provided by the user. The function yylex() is automatically generated by the flex when it is provided with a . l file and this yylex() function is expected by parser to call to retrieve tokens from current/this token stream.

What is the difference between bison and yacc?

Bison is the GNU implementation/extension of Yacc, Flex is the successor of Lex. In either case, it's fine (and recommended) to use bison / flex. Additionally, byacc, the Berkeley implementation of yacc, is widely available (I see it in my Debian repository list).


1 Answers

Yes.

Have a top level rule which just does the assignment:

%%
    toplev:   expr                    { res = $1; }
    expr:     expr PLUS expr          { $$=evaluate("+",$1,$3);}
           |  expr MINUS expr         { $$=evaluate("-",$1,$3);} 
%%
like image 141
Martin York Avatar answered Sep 21 '22 09:09

Martin York