Home > Blockchain >  flex/bison gives me a syntax error after printing the result and if another input is written to work
flex/bison gives me a syntax error after printing the result and if another input is written to work

Time:07-30

After running the compiler and type the entry on, works fine. Then if I type another entry (and if it also works ok) it gave me Syntax Error. I must mention I am a new in ​​the world of flex/bison. To be honest I do not know what's could be wrong, some one please help?

Here is my lex code:

%{
  #include <stdio.h>
  #include "calc.tab.h"
  void yyerror(char *);
%}

%option noyywrap

DIGIT -?[0-9]
NUM -?{DIGIT} 


%%

{NUM}       { yylval = atoi(yytext); return NUMBER; }
[-() */;]   { return *yytext; }
"evaluar"   { return EVALUAR; }
[[:blank:]] ;
\r        {}
.           yyerror("caracter invalido");

%%

and here it is my bison code:

%{
    
    #include <stdio.h>
   
    int yylex(void);
    void yyerror(char *s);    
%}

%token NUMBER EVALUAR 

%start INICIO

%left ' ' '-'

%left '*' '/'

%%

    INICIO
        : EVALUAR '(' Expr ')' ';'
        {
            printf("\nResultado=%d\n", $3);
            

        }
    ;

    Expr
        : Expr ' ' Expr
        {
            $$ = $1   $3;
        }

        | Expr '-' Expr
        {
            $$ = $1 - $3;
        }

        | Expr '*' Expr
        {
            $$ = $1 * $3;
        }

        | Expr '/' Expr
        {
            $$ = $1 / $3;
        }

        | NUMBER
        {
            $$ = $1;
        }
    ;

%%

int main(){
 
    return(yyparse());
}

void yyerror(char *s){
    printf("\n%s\n", s);
}

int yywrap(){
    return 1;
}

Here is an example of the output:

C:\Users\Uchih\Desktop\bison>a evaluar(2 3);

Resultado=5

evaluar(3 2);

syntax error

CodePudding user response:

Your parser is written to accept a single input INICIO rule/clause, after which it will expect an EOF (and will exit after it sees it). Since instead you have a second INICIO, you get a syntax error message.

To fix this, you want your grammar to accept one or more things. Add a rule like this:

input: INICIO | input INICIO ;

and change the start to

%start input
  • Related