Search code examples
cbisonflex-lexer

Flex/Bison program gives Syntax Error message


I recently started learning using flex and bison together for a project I am doing. Program is about interval arithmetics. It takes 2 values with either open or closed brackets, then prints out the interval of array that is defined in the bison file. This is the flex file:

%{
    #include <stdio.h>
    #include <string.h>
    #include "bis.tab.h"
%}

numbers ([0-9])+

%%
{numbers} { yylval.n = atoi(yytext); return NUMBER; }
"["   { return LEFTCLOSE; }
"]"   { return RIGHTCLOSE; }
"("   { return LEFTOPEN; }
")"   { return RIGHTOPEN; }
":"   { return MID; }
[ \t\n] { ; }
.      { printf("Mystery character %c\n", *yytext); }
%%

int yywrap(void){
    return 1;
}

This is the bison file:

%{
    #include <stdio.h>
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
%}

%token <n> NUMBER
%token LEFTOPEN RIGHTOPEN LEFTCLOSE RIGHTCLOSE
%token MID

%type <n> E T

%union {
    int n;
    int ar[10];
}

%%

O: 
 | LEFTOPEN E MID T RIGHTOPEN    {for(int i = $2; i<$4-1; i++){printf("%d ", arr[i]);}  printf("\n");  }
 | LEFTCLOSE E MID T RIGHTCLOSE  {for(int i = $2-1; i<$4; i++){printf("%d ", arr[i]);}  printf("\n");  }
 ;

E: NUMBER                        {$$ = $1}
 ;

T: NUMBER                        {$$ = $1}
 ;

%%

int main(int argc, char** argv) {
    yyparse();
    return 0;
}


void yyerror(const char* msg) {
    fprintf(stderr, "ERROR! %s\n", msg);
}

And here is the output I get:

> C:\Users\shahi\Desktop\flexbison\simplearithmetics>test.exe
> (1:5) //input
> 2 3 4 //output
> [1:5] //input
> ERROR! syntax error

Solution

  • sepp2k got it right in his or her comment: The grammar is single "statement" only.

    To be able to handle multiple lines or "statements" you need to use recursive rules like

    many_O: O
          | O many_O
          ;
    
    O: ...