问题描述
我最近开始学习将 flex 和 bison 一起用于我正在做的一个项目。程序是关于区间算术的。它需要 2 个带左括号或右括号的值,然后打印出野牛文件中定义的数组的间隔。这是 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 = $2; i<$4-1; i++){printf("%d ",arr[i]);} printf("\n"); }
| LEFTCLOSE E MID T RIGHTCLOSE {for(int i = $2-1; i<$4; i++){printf("%d ",arr[i]);} printf("\n"); }
;
E: NUMBER {$$ = $1}
;
T: NUMBER {$$ = $1}
;
%%
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: ...