Reputation: 1506
I am observing a weird behavior while using lex and yacc.
Here is my lex file -- ex.l
%option noyywrap
%option yylineno
%{
#include <iostream>
using namespace std;
#include "y.tab.h"
void yyerror(char *); // to get the token types that we return
%}
%%
[ \t] ;
[0-9]+\.[0-9]+ { yylval.fval = atof(yytext); //this is not working
cout << "lex found an float: "; return FLOATS; }
[0-9]+ { cout << "lex found an int: "; yylval.ival = atoi(yytext); return INTS; }
[a-zA-Z0-9]+ {
char *res = new char[strlen(yytext) + 1];
strcpy(res, yytext);
yylval.sval = res;
return STRINGS;
}
. ;
%%
hHre is my yacc file -- ex.y
%{
#include <iostream>
using namespace std ;
extern int yylex();
extern int yyparse();
extern FILE *yyin;
extern int yynerrs;
extern void yyerror(char *s);
%}
%union {
int ival;
float fval;
char *sval;
}
%token <ival> INTS
%token <fval> FLOATS
%token <sval> STRINGS
%%
grammar:
INTS grammar { cout << "yacc found an int: " << $1 << endl; }
| FLOATS grammar { cout << "yacc found a float: " << $1 << endl; }
| STRINGS grammar { cout << "yacc found a string: " << $1 << endl; }
| INTS { cout << "yacc found an int: " << $1 << endl; }
| FLOATS { cout << "yacc found a float: " << $1 << endl; }
| STRINGS { cout << "yacc found a string: " << $1 << endl; }
;
%%
#include <stdio.h>
main() {
yyin = stdin;
do {
yyparse();
} while (!feof(yyin));
}
void yyerror(char *s) {
cout << "EEK, parse error! Message: " << s << endl;
exit(-1);
}
After compiling these two and running them, I don't get the output from the lex for ex:-
Why is it happening? Why isn't cout statement in action of lex working?
Upvotes: 2
Views: 329
Reputation: 360
The trouble is I think the following code in ex.y.
%token <ival> INTS
%token <fval> FLOATS
%token <sval> STRINGS
There the inbuilt tokens are used. That overrides the tokens defined in ex.l file. In a sense, the execution never reaches the cout lines in ex.l file.
Try writing only following code & it should work.
%token INTS
%token FLOATS
%token STRINGS
Hope this helps.
NOTE: I have not tested the code. So you may get other errors after doing this.
Upvotes: 1