0
votes

Using the following flex and bison code, I can print the text hello when the command print "Hello" is inputted:

flex file:

%{
#include <iostream>
using namespace std;
#define YY_DECL extern "C" int yylex()
#include "gbison.tab.h"
%}
%%
[ \t\n]            ;
[a-zA-Z0-9]+       { yylval.sval = strdup(yytext); return STRING; }
\"(\\.|[^"])*\"    { yylval.sval = strdup(yytext); return QUOTED_STRING; }
%%

bison file:

%{
#include <cstdio> 
#include <cstring>
#include <iostream>
using namespace std;

extern "C" int yylex();
extern "C" int yyparse();
extern "C" FILE* yyin;

void yyerror (const char* s);
%}

%union {
  char* sval;
}

%token <sval> STRING
%token <sval> QUOTED_STRING
%%

str:
    STRING QUOTED_STRING
    {
       if (strcmp($1, "print") == 0)
       {
           cout << $2 << flush;
       }
       if (strcmp($1, "println") == 0)
       {
           cout << $3 << endl; 
       }
    }
    ;
%%

main(int argc, char* argv[])
{
   FILE* input = fopen(argv[1], "r");
   if (!input)
   {
      cout << "Bad input. Nonexistant file" << endl; 
      return -1;
   } 

   yyin = input;

   do 
   {
       yyparse();
   } while (!feof(yyin));

}
void yyerror(const char* s)
{
   cout << "Error. " << s << endl; 
   exit(-1);   
}

How would I change the Bison grammar so that it would not have a syntax error if there is more than one print or println command?

1
Please be careful of tagging... Flex is for the Adobe/Apache UI Framework. Flex-lexer is for the lexical analyzer.JeffryHouser
@Reboog711 Got it. Didn't realize that flex is for Adobe/Apache Flex, not the flex-lexerinixsoftware

1 Answers

1
votes

Add to the grammar before the first %% line:

%start list

and add to the grammar just after the first %% line:

list:
        /* Nothing */
    |   list str
    ;

This says that the complete grammar consists of a list, and a list is nothing (empty input) or a list followed by a 'str'.

As it stood, your grammar said that the valid inputs consisted of exactly one occurrence of 'str', hence the syntax error when you started to repeat yourself.