0

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;
}
Community
  • 1
  • 1
CJAN.LEE
  • 1,108
  • 1
  • 11
  • 20
  • I'm curious, why `yylval = atoi("0");` instead of just `yylval = 0;`? Seems a bit inefficient... – twalberg Sep 21 '12 at 16:09
  • Oh, sorry, I will modify it, actually, today is the first time I wrote lex yacc – CJAN.LEE Sep 21 '12 at 16:13
  • See [this](http://stackoverflow.com/questions/780676/string-input-to-flex-lexer) for how to get a lexer to read from a string instead of a file. – twalberg Sep 21 '12 at 16:26

0 Answers0