I am trying to use Flex to parse 'C' source code. Unfortunately I am getting the error "expected identifier or '(' before '{' token" on lines 1,12,13,14... . Any ideas why?
%{
%}
digit [0-9]
letter [a-zA-Z]
number (digit)+
id (letter|_)(letter|digit|_)*
integer (int)
character (char)
comma [,]
%%
{integer} {return INT;}
{character} {return CHAR;}
{number} {return NUM;}
{id} {return IDENTIFIER;}
{comma} {return ',';}
[-+*/] {return *yytext;}
. {}
%%
main()
{
yylex();
}
The corresponding flex file is as shown below:
%{
#include <ctype.h>
#include <stdio.h>
#include "myhead.h"
#include "mini.l"
#define YYSTYPE double
# undef fprintf
%}
%token INT
%token CHAR
%token IDENTIFIER
%token NUM
%token ','
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
lines:lines expr '\n' {printf("%g\n",$2);}
|lines '\n'
|D
|
;
expr :expr '*' expr {$$=$1*$3;}
|expr '/' expr {$$=$1/$3;}
|expr '+' expr {$$=$1+$3;}
|expr '-' expr {$$=$1+$3;}
|'(' expr ')' {$$=$2;}
|'-' expr %prec UMINUS {$$=-$2;}
|IDENTIFIER {}
|NUM {}
;
T :INT {}
|CHAR {}
;
L :L ',' IDENTIFIER {}
|IDENTIFIER {}
;
D :T L {printf("T is %g, L is %g",$1,$2);}
;
%%
/*void yyerror (char *s)
{
fprintf (stderr, "%s\n", s);
}
*/
I am compiling the generated code using the command:
gcc my_file.c -ly