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?
flex
is for Adobe/Apache Flex, not theflex-lexer
– inixsoftware