Reputation: 25
I'm trying to connect simple flex and bison code that would just recognize a character for now. Yet I'm facing this error. I've read through a lot of answers to figure out what is wrong but am lost. Any help would be highly appreciated as I'm just starting out to explore this and could not find a lot of resources for it.
This is my .l file
%{
#include <stdlib.h>
#include <stdio.h>
#include "MiniJSC.tab.h"
void yyerror (char *s);
int yylex();
%}
%%
[0-9]+ { yylval.num = atoi(yytext); return T_INT_VAL; }
%%
int yywrap (void) {return 1;}
my .y file
%{
void yyerror (char *s);
int yylex();
#include <stdio.h> /* C declarations used in actions */
#include <stdlib.h>
%}
%union {int num; char id;} /* Yacc definitions */
%start line
%token print
%token T_INT_VAL
%type <num> line
%type <num> term
%type <num> T_INT_VAL
%%
/* descriptions of expected inputs corresponding actions (in C) */
line : print term ';' {printf("Printing %d\n", $2);}
;
term : T_INT_VAL {$$ = $1;}
;
%% /* C code */
void yyerror (char *s) {
fprintf (stderr, "%s\n", s);
}
int main (void) {
return yyparse ( );
}
The compilation and output:
$ bison MiniJSC.y -d
$ lex MiniJSC.l
$ gcc lex.yy.c MiniJSC.tab.c
$ ./a.out
10
syntax error
$
Upvotes: 0
Views: 36
Reputation: 370425
line : print term ';'
According to this, a valid line contains a print
token followed by a term
. Since a term
must be a T_INT_VAL
token, that means a valid line is a print
token followed by a T_INT_VAL
token.
Your input consists only of a T_INT_VAL
token, so it is not a valid line and that's why you get a syntax error.
Also note that your lexer never produces a print
token, so even if you entered print 10
as the input, it'd be an error since the lexer isn't going to recognize print
as a token. So you should add a pattern for that as well.
You should also rename print
to match your naming convention for tokens (i.e. ALL_CAPS).
Upvotes: 1