Domanda

I have a simple project using flex/bison. I'm trying to parse a text file, but it doesn't quits parsing (apparently a loop at end of file).

My flex code:

%{
#include "y.tab.h"
%}
%%
[0-9]                           { printf("digit: %s\n",yytext); return DIGIT; }
[a-zA-ZáéíóúÁÉÍÓÚçÇãõÃÕ]+       { printf("word: %s\n",yytext); return WORD; }

[\.]                            
[ ]        
[\n]             

.                               { printf("other: %s\n",yytext); return OTHER; }

<<EOF>>                         { yyterminate(); return 0; }
%%

My bison code:

%{
#include <stdio.h>
#include <stdlib.h>
%}

%token DIGIT WORD OTHER SPACE

%%
start :
    text
    ;

text :
    | WORD text
    ;

%%

extern FILE *yyin;

main()
{
    printf("Translating...\n");
    printf("\n");

    if ((yyin = fopen("/home/nilo/text","r")) == NULL)
    {
        fprintf(stderr,"File not found or not readable.\n");
        exit(1);
    }

    // Start the parser
    yyparse();

    fprintf(stderr,"Parser ended...\n");
}

yyerror(s)
char *s;
{
    printf("yacc error: %s\n", s);
}

yywrap()
{
    return(0);
}

I've already tried not to put <<EOF>> rule and some other things related to this, like calling yyterminate(), calling return 0, both things, etc., but no success.

Can someone tell me what I'm missing?

TIA.

È stato utile?

Soluzione

Ok, got it working...

When I initially started to play with this code, I did it using the famous "ctrl-c/ctrl-v" feature... :)

When "yywrap()" return 0, this indicates that the EOF had been reached but the parsing must continue. This is particularly true on interactive parsers.

Getting input from a file, as it's the present situation, we have 3 alternatives to quit the parsing on end-of-file situation:

  1. Put an %option noyywrap on lex specifications and remove the yywrap() code on your side OR
  2. Change your yywrap() to returns 1 to quit parsing OR
  3. Change your yywrap() to set yyin to another file and returns 0 to continues parsing the newly added file.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top