0

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
  • 1
    Unrelated to your problem, but the normal style conventions is that non-terminal symbols in the YACC or Bison grammar are lower-case. It makes it easier to distinguish between terminal and non-terminal symbols, making the grammar easier to read and understand. I also recommend you start with the plain grammar without semantic statements or types, as it also makes it easier to read the grammar to help finding problems like yours. – Some programmer dude Mar 09 '21 at 15:50
  • @Someprogrammerdude Thanks for the tips! Still a long way for me to learn. – Shahin Mammadov Mar 09 '21 at 15:55
  • 2
    As far as I can tell, your first and last line of input should parse correctly if you entered one of them on its own, but your grammar simply doesn't allow multiple expressions. Your middle line (`2 3 4`) just doesn't seem to match your grammar. – sepp2k Mar 09 '21 at 15:58
  • @sepp2k: `2 3 4` is output. After parsing the `(1:5)`, the grammar calls `printf()`. – Bill Lynch Mar 09 '21 at 16:00
  • I added comments in the output so its easy to see what is input and what is output. – Shahin Mammadov Mar 09 '21 at 16:02

1 Answers1

1

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: ...
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621