최근에 GNU Bison
및 Flex
을 사용하여 인터프리터를 작성하려고했습니다. 내가 인터프리터가 인식 할 텍스트는 print "Hello"
이고, 나는 다음과 같은 시도 :Bison/Flex 구문 분석 파일
flex file:
%{
#include <iostream>
using namespace std;
#define YY_DECL extern "C" int yylex()
#include "gbison.tab.h"
%}
%%
[ \t\n] ;
'\"' return QUOTE;
[a-zA-Z0-9]+ { yylval.sval = strdup(yytext); return 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 QUOTE
%%
str:
STRING QUOTE STRING QUOTE
{
if (strcmp($1, "print") == 0)
{
cout << $3 << 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 "hello"
을 통과 할 때 내가 얻을 : 를 "Error. syntax error
나는 그쪽으로 생각한다. 문제는 STRING QUOTE STRING QUOTE
이지만 확실하지 않습니다. 정확하게 무엇이 잘못 될까요? 통역사에게 hello
을 인쇄하게하려면 어떻게해야합니까?