I m working on a simple interpreter and I m using bison and flex for my lexer and parser.I have a problem when it comes to the parser :
progr :decl_classes decl_gvars decl_functions block {printf("The programme is correct!\n");}
;/*1. classes 2.global vars 3.functii 4.enetry point*/
decl_classes :decl_class ';' decl_classes
|{cout<<"No more classes\n";}
;
decl_class :CLASS ID '{' decl_gvars decl_functions '}' {cout<<"We have a class :"<<$2<<"\n";}
;
decl_functions :{cout<<"No more functions\n";}
|decl_function ';' decl_functions
;
decl_function :TYPE ID '('list_param')' '{'list'}'
;
decl_gvars :decl_gvar ';' decl_gvars
|{cout<<"No more gvars\n";}
;
decl_gvar :typedecl list_ID {cout<<"We have vars "<<endl;}
;
typedecl : TYPE {cout<<"Try to make a var\n";}
;
list_ID : ID '[' expr ']'
| ID
| ID ',' list_ID
;
list_param :param ',' list_param
|/*none*/
;
param :typedecl ID
|typedecl ID '['expr']'
;
block : BGIN list END
;
list : statement ';'
| list statement ';'
|/*none*/
;
the parser will always chose to make decl_gvar instead of decl_function. Any help would be apriciated.
I tested if the parser will make my decl_function if it s isolated and it does.
The basic problem is that after seeing a
TYPEwhen the next token is anIDit doesn't yet know if it is looking at a decl_function or a decl_gvar, but your grammar forces it to reduce atypedeclto recognize a decl_gvar or not reduce it to recognize a decl_function. This results in a shift/reduce conflict (which bison should report). Since it will by default do the shift in preference to the reduce, the parser will always try to parse this as a decl_function, even if it is in fact a decl_gvar (and will in that case get a syntax error.)The easiest fix is to get rid of of the
typedecl : TYPErule (and replacetypedeclwithTYPEin the decl_gvar rule.) This way, you don't need the reduction and things will be deferred until after theIDtoken, so it will be able to see a(to recognize a function or a,or;to recognize a gvar.