0
使用下面的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);
}
如何我会改变Bison grammar
以便它会如果有多个print或println命令,没有语法错误?
请注意标注的... Flex是用于Adobe/Apache的UI框架。 Flex-lexer用于词法分析器。 – JeffryHouser
@ Reboog711明白了。没有意识到'flex'是用于Adobe/Apache Flex的,而不是'flex-lexer' – inixsoftware