I'm doing an assignment, where I have to make Bison/Flex app that would append while/if case beginning at the end every case as a comment. I've managed to compile all the components together, but no matter what I do, it always throws an error after trying to parse the second token.
I'm using Windows versions of Bison and Flex (2.4.1 and 2.5.4a-1 respectively)
Here's my lex file commentAdder.l
%{
#include "commentAdder.tab.h"
%}
%option noyywrap
CLOSE "}"
CASE ("while"|"if"|"switch")(" "|"")("(".+")")(" {"|"{")
CODE .+
%%
{CLOSE} {yylval.s=yytext; return CLOSE;}
{CASE} {yylval.s=yytext; return CASE;}
{CODE} {yylval.s=yytext; return CODE;}
%%
And my parser commentAdder.y
%{
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_DEPTH 10
#define MAX_COMMENT_LENGTH 32
int yylex();
void yyerror( char* );
extern char* yytext;
/* Local variables */
char heldComments[MAX_DEPTH][MAX_COMMENT_LENGTH] = {};
int currentDepth=-1;
%}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
%union {
char* s;
}
%token <s> CASE CLOSE CODE
%type <s> expr
%% /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
expr : CLOSE {$$ = strcat($1,(char *)strcat((char *)"//",heldComments[currentDepth]));
strcpy(heldComments[currentDepth],"");
printf("CLOSE: ",$1);
currentDepth=currentDepth-1;}
| CASE {$$=$1; currentDepth=currentDepth+1; strcpy(heldComments[currentDepth],$1); printf("CASE: ",$1);}
| CODE {printf("CODE: ",$1);$$=$1;}
;
%% /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
void yyerror( char* s )
{
fprintf(stderr,"Unexpected token: '%s'\n",yytext);
exit(1);
}
int main() {
yyparse();
return 0;
}
I'm guessing that expr has nowhere to go after the first parse leaving it with no room for further arguments, but I've no idea how to fix that since I'm a complete novice to this and tutorials are overcomplicated and scarce.
UPDATE
With help of Rici's I've fixed the issue by changing grammar section in parser to this:
input : expr {}
| input expr
expr : CLOSE {if(currentDepth>=0){
$$ = strcat($1,(char *)strcat((char *)"//",heldComments[currentDepth]));
.
.
.
Now I have a whole different problem where strcat for some reason causes app to end prematurely, presumably due to error of some kind.
adder : expr | adder expr | CLOSE {$$ = str...
– Ozzzimexpr
without a flood of error messages. – rici