I am working on a Flex and Bison project. I did a great job with my flexibility and bison, but I'm trying to give argv as input (yyin). So I changed yyin so that it takes argv [1], but it actually doesn't work. It seems like he took argv [1], but then I got a syntax error, even if my line, I suppose, works fine.
Here is my flex:
%{
#include "parser.hpp"
extern int yyparse();
%}
%option noyywrap
texte [a-zA-z]+
entier [0-9]+(\.[0-9])?
%%
{entier} { yylval.num = atoi(yytext); return(NUMBER);}
"pi" return(PI);
"," return(SEP);
"(" return(OP);
")" return(CP);
"+" return(ADD);
"-" return(SUB);
"*" return(MUL);
"/" return(DIV);
"%" return (MODULO);
"sin" return(SIN);
"cos" return(COS);
"tan" return(TAN);
"acos" return(ACOS);
"asin" return(ASIN);
"atan" return(ATAN);
"sqrt" return(ROOT);
"pow" return(POW);
"exp" return(EXP);
"\n" return(END);
{texte} return(ERROR);
%%
Then my bison (I did not implement COS SIN and others so that it would be easiest to read):
%defines
%{
#include <iostream>
#include <math.h>
using namespace std;
extern int yylex();
extern void yyerror(char const* msg);
%}
%union {double num;}
%token <num> NUMBER PI
%token OP CP SEP END
%token COS SIN TAN
%token ACOS ASIN ATAN
%token ADD SUB
%token MUL DIV
%token ROOT POW MODULO EXP ABS
%left ADD SUB
%left MUL DIV
%token ERROR
%type <num> calclist exp factor term
%start calclist
%%
calclist:
| calclist exp END {cout << $2 << endl;}
;
exp: factor
| exp ADD factor { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: NUMBER
| OP exp CP {$$ = $2;}
;
%%
extern void yyerror(char const* msg){
cerr << "Error " << msg << endl;
}
Then my main:
#include <iostream>
#include "parser.hpp"
#include <string.h>
using namespace std;
extern FILE *yyin;
extern int yy_scan_string(const char *);
int main(int argc, char const *argv[]) {
yy_scan_string(argv[1]);
return yyparse();
}
and finally my makefile:
all: bison flex main.cpp
g++ parser.cpp lexer.cpp main.cpp -o parser
rm lexer.cpp parser.cpp parser.hpp
./parser "(1+2)"
bison: parser.y
bison -o parser.cpp parser.y
flex: lexer.l
flex -o lexer.cpp lexer.l
I tried too ./parser (1+2), but I got more errors. Thanks for the help!
source
share