Flex/Bison 程序给出语法错误消息

Flex/Bison program gives Syntax Error message

我最近开始学习将 flex 和 bison 一起用于我正在做的项目。程序是关于区间运算的。它需要 2 个带有左括号或右括号的值,然后打印出在 bison 文件中定义的数组间隔。这是 flex 文件:

%{
    #include <stdio.h>
    #include <string.h>
    #include "bis.tab.h"
%}

numbers ([0-9])+

%%
{numbers} { yylval.n = atoi(yytext); return NUMBER; }
"["   { return LEFTCLOSE; }
"]"   { return RIGHTCLOSE; }
"("   { return LEFTOPEN; }
")"   { return RIGHTOPEN; }
":"   { return MID; }
[ \t\n] { ; }
.      { printf("Mystery character %c\n", *yytext); }
%%

int yywrap(void){
    return 1;
}

这是野牛文件:

%{
    #include <stdio.h>
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
%}

%token <n> NUMBER
%token LEFTOPEN RIGHTOPEN LEFTCLOSE RIGHTCLOSE
%token MID

%type <n> E T

%union {
    int n;
    int ar[10];
}

%%

O: 
 | LEFTOPEN E MID T RIGHTOPEN    {for(int i = ; i<-1; i++){printf("%d ", arr[i]);}  printf("\n");  }
 | LEFTCLOSE E MID T RIGHTCLOSE  {for(int i = -1; i<; i++){printf("%d ", arr[i]);}  printf("\n");  }
 ;

E: NUMBER                        {$$ = }
 ;

T: NUMBER                        {$$ = }
 ;

%%

int main(int argc, char** argv) {
    yyparse();
    return 0;
}


void yyerror(const char* msg) {
    fprintf(stderr, "ERROR! %s\n", msg);
}

这是我得到的输出:

> C:\Users\shahi\Desktop\flexbison\simplearithmetics>test.exe
> (1:5) //input
> 2 3 4 //output
> [1:5] //input
> ERROR! syntax error

sepp2k 在他或她的评论中说对了:语法只是单个“语句”。

为了能够处理多行或“语句”,您需要使用递归规则,例如

many_O: O
      | O many_O
      ;

O: ...