-   Programming (
-   -   [flex & bison] Why does my rule fail from line 2? (

chuanyung 07-30-2004 04:21 AM

[flex & bison] Why does my rule fail from line 2?
Dear all,

I am a newbie to use flex and bison.
I don't know how to solve this problem.
My test file has 2 lines which are same.
I can match my rule in first line, but fail in second line.
What's wrong?

And when I need to use loop to yyparse() many times?
Please help, thanks.

Here are my files.

test abc 10 def
test abc 10 def

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "bison.h"
int mylineno=1;
bool isEOF=false;
extern void yyerror(char* szErrorMessage);

%option noyywrap
%option outfile="flex.c"
%option yylineno

%x stTEST

white ([ \t\r]+)
digit ([0-9])
letter ([a-zA-Z])
eol (\r?\n)


{white} ;

test{white} {printf("Begin test:\n");BEGIN stTEST;return TEST;}
<stTEST>{white} ;
<stTEST>{digit}+ {yylval.INT=atoi(yytext); printf("Got integer %d\n",yylval.INT);return INTEGER;}
<stTEST>{letter}+ {yylval.STR=strdup(yytext);printf("Got string %s\n",yylval.STR);return TEXT;}
<stTEST>{eol} {printf("Got eof in test\n");BEGIN INITIAL; return EOL;}
<stTEST>. {yyerror("Not an alpha number!");yyterminate();}

. {yyerror("Not a test command\n");yyterminate();}
{eol} {mylineno++;}

<<EOF>> {isEOF=true;printf("end of file\n");return 0;}


#include <stdio.h>
extern FILE* yyin;
extern int yylineno;
extern int yylex(void);
extern int mylineno;
extern bool isEOF;
void yyerror(char* szErrorMessage);

%union {
int INT;
char* STR;
/* options */
/* end of options*/

%token <INT> INTEGER
%token <STR> TEXT
%token EOL /* end of line */
%token TEST


start: test {printf("test command is ok.\n");}

test: test_expression EOL {mylineno++};

test_expression: TEST TEXT INTEGER TEXT

int main(int argc,char* argv[])
if (argc<2) {
printf("No file to parse\n");
return -1;

if (yyin==NULL) {
printf("Fail to open file %s\n",argv[1]);
return -2;


return 0;

void yyerror(char* szErrorMessage)
printf("My error in %d: %s.\n",mylineno,szErrorMessage);

test: bison.o flex.o
g++ -o test bison.o flex.o -lfl -ly -lm

bison.o: bison.c bison.h
g++ -c bison.c

flex.o: flex.c bison.h
g++ -c flex.c

bison.c: bison.y
bison -d bison.y

flex.c: flex.l
flex -L flex.l

rm -rf *.o flex.c bison.c bison.h test test.exe

All times are GMT -5. The time now is 11:20 AM.