Possible Duplicate:
Good tools for creating a C/C++ parser/analyzer
String input to flex lexer
My idea is to create a parser that can calculate the expression of Boolean, and my next step is to use it in my c++ program, but I don't know how to use it.
Currently, this calculator can run in command line, the code is not good, and I don't know how to use it in my program. I want to use a function lex_yacc(var)
to call this calculator, and var
is the input, for example, the main program read the var
is (T+F)
, so it will be sent to lex_yacc(var)
, finally, the func returns 1
.
I define the lexya.l as follows:
%{
#include <stdlib.h>
void yyerror(char *);
#include "lexya_a1.tab.h"
%}
%%
"T" { yylval = 1; return boolean; }
"F" { yylval = 0; return boolean; }
"!F" { yylval = 1; return boolean; }
"!T" { yylval = 0; return boolean; }
[+*\n] return *yytext;
"(" return *yytext;
")" return *yytext;
[\t] ;/* .... */
. yyerror("....");
%%
int yywrap(void) {
return 1;
}
And lexya_a1.y:
%{
#include <stdlib.h>
int yylex(void);
void yyerror(char *);
%}
%token boolean
%left '+' '-'
%left '*'
%left '(' ')'
%%
program:
program expr '\n' { printf("%d\n", $2); }
|
;
expr:
boolean { $$ = $1; }
| expr '*' expr { $$ = $1 * $3; }
| expr '+' expr { $$ = $1 + $3; }
| '(' expr ')' { $$ = $2; }
;
%%
void yyerror(char *s) {
printf("%s\n", s);
}
int main(void) {
yyparse();
return 0;
}