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