I'm trying to implement a simple lexer and parser using flex-bison.
All I wanted is parse these :
- a
- a,b
- a ,b
- a, b
- a,b,c
- a,b , c
- ....
Just a sequence separated with comma, may or may not contain space. So here is my grammar :
KEY_SET : KEY
{
printf("keyset 1");
}
| KEY COMMA KEY_SET
{
printf("keyset 2");
};
Declared KEY
, COMMA
as token
.//%token
But it gives me Syntax Error, whenever I press enter or any whitespace.
So I even declared IGNORE [ \t\n]
in flex.
And in parser I added a new rule :
IGNORE_BLOCK : IGNORE
{
printf("\n...ignoring...\n")
};
But this doesn't even come to play.
It keeps me giving Syntax Error.
How can I resolve this ?
Lexer :
%{
#include "y.tab.h"
%}
%option noyywrap
COMMA [,]
KEY [[:alpha:][:alnum:]*]
IGNORE [ \t\n]
%%
{COMMA} {return COMMA;}
{KEY} {return KEY;}
{IGNORE} {return IGNORE;}
. {printf("Exiting...\n");exit(0);}
%%
Parser :
%{
#include<stdio.h>
void yyerror (char const *s);
int yywrap();
//int extern yylex();
%}
%token COMMA
%token KEY
%token IGNORE
%%
KEY_SET : KEY
{
printf("keyset 1");
}
| KEY COMMA KEY_SET
{
printf("keyset 2");
};
IGNORE_BLOCK : IGNORE
{
printf("\n...ignoring...\n")
};
%%
int main(int argc, char **argv)
{
while(1)
{
printf("****************\n");
yyparse();
char ign;
scanf("%c",&ign);
}
return 0;
}
int yywrap()
{
return 1;
}
void yyerror (char const *s) {
fprintf (stderr, "%s\n", s);
}
Command I'm using to build :
flex test.l
bison -dy test.y
gcc lex.yy.c y.tab.c -o test.exe