使用以下代码flex
和代码,我可以在输入命令时bison
打印文本:hello
print "Hello"
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);
}
如果有多个 print 或 println 命令,我将如何更改Bison grammar
它以使其不会出现语法错误?