Midhun Midhun - 3 months ago 13
C Question

YACC-generated parser gives different outputs for same input repeated

I want to check a string, if it matches the grammar

a^nb^n
using YACC and LEX. Here are my LEX and YACC files in same order:

Lex file:

%{
#include <stdio.h>
#include <y.tab.h>
%}

%%
a {return A;}
b {return B;}
. {return yytext[0];}
\n {return NL;}
%%
int yywrap(void) {
return 1;
}


YACC file:

%{
#include <stdio.h>
yyerror()
{
printf("Rejected\n");
}
%}

%token A B NL
%start T

%%

T : S NL {printf("accepted\n");}
;
S : A S B
| A B
;

%%

main()
{
yyparse();
}


The problem is the output:

input string: aabb

output: Accepted

input string: aabb

output: Rejected

When the same input or any input that is suppose to be accepted answer is rejected when entered second time. I learned that YACC has a stack that it uses when it parses the string. But i couldn't find any document regarding that. Please help.

Answer

The yacc rule T is non-recursive, meaning that it only matches one line. The following modification will watch any number of lines (including none).

T : T S NL
  | /* empty */
  ;

Resulting in consecutive lines being accepted.

$ printf 'aabb\naabb\n' | ./a.out
accepted
accepted
Comments