sengineer23
sengineer23

Reputation: 33

Bison/Flex parsing issue

I am working with bison and flex and am currently have some issues. Currently the first character is read and passed to Bison, but immediately yyerror() is thrown. It should print 1 as 'w' is an Ident defined by my Flex rules.

I cannot identify the source of the issue. I am inexperienced using Bison.

Here are my bison parsing rules:

    %%

   Prog : StmtSeq               {printf("13");};
   StmtSeq : Stmt StmtSeq           {printf("12");};
   StmtSeq :                        {printf("11");}; 
   Stmt : Id ':' Expr       {printf("10");}; 
   Expr : Expr '+' Term     {printf("9");}; 
   Expr : Term                  {printf("8");}; 
   Term : Term '*' Factor   {printf("7");};
   Term : Factor                {printf("6");};
   Factor   : '(' Expr ')'          {printf("5");}; 
   Factor   : '{' Expr '}'          {printf("4");}; 
   Factor   : Id                    {printf("3");}; 
   Factor   : SetLit                {printf("2");};
   Id       : Ident                 {printf("1");};

   %%

Here is my flex grammar:

    {letter} {return Ident;}
    (\{\})|(\{{letter}(\,{letter})*\}) {return SetLit;} 
    \( {return '(';}
    \) {return ')';}
    \* {return '*';}
    \+ {return '+';}
    \{ {return '{';}
    \} {return '}';}
    \: {return ':';}
    [ ]             {return;}
    \t              {return;}
    \r              {return;}
    \n              {return;}
    . {writeIndicator(getCurrentColumnNum()); writeMessage("Illegal Character in lex"); }

The input is a .txt file that contains:

  w: {f,x,a,b,c,d,e}
  x: {f,a,b,c,d,e}
  y: {}
  z: {x}
  a: {f,x,a,b,c,d,e}
  b: {}  

Upvotes: 1

Views: 322

Answers (1)

rici
rici

Reputation: 241911

If you want lex to ignore a token, the pattern which matches that token should do nothing. return does not do nothing; it causes yylex to return. Furthermore, it is undefined behaviour because you haven't specified the value yylex should return. (Compiling with -Wall might have caught this problem.)

So when the scanner reads a space, it returns some unspecified value to the caller (yyparse). Naturally, this doesn't work as expected.

Change (for example)

[ ]             {return;}

To

[ ]             ;

Or, better, replace that sequence of redundant rules with

[[:space:]]+    ;

Upvotes: 3

Related Questions