bison rule useless in grammar

Bison warning: noterminal useless in grammar [-Wother]

起因

看了bison文档example的那一部分所以想要凭记忆写一个简单的计算器,于是有了如下代码

%{

#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
int yylex (void);
void yyerror (char const *);

%}

%define api.value.type {double}
%left '+' '-'
%left '*' '/'

%token NUM
%%


expr: NUM
	| expr '+' expr		{/*printf("%.2f + %.2f\n",$1,$3);*/$$=$1+$3;}
	| expr '-' expr		{/*printf("%.2f - %.2f\n",$1,$3);*/$$=$1-$3;}
	| expr '*' expr		{/*printf("%.2f * %.2f\n",$1,$3);*/$$=$1*$3;}
	| expr '/' expr		{/*printf("%.2f / %.2f\n",$1,$3);*/$$=$1/$3;}
	| '(' expr ')'		{/*printf("( %f )\n",$2);*/$$=$2;}

line: expr '\n'			{printf("The answer is %f\n",$1);}
	| '\n'

lines: line lines
	|

%%
int main() {
	yyparse();
	return 0;
}

void yyerror(char const *s){
	printf("%s\n",s);
}

int valid(char c){
	return c=='+'||c=='-'||c=='*'||c=='/'||c=='\n'||c=='('||c==')'||c==';';
}
int yylex(void){
	char c;
	while((c=getchar())!=EOF && (c==' '||c=='\t'));
	if(valid(c))return c;
	if(c=='.'||isdigit(c)){//parse the float
		float v=0,f=1;
		while(c!=EOF && (c=='.' || isdigit(c))){
			if(f==1){
				if(c=='.')f/=10;
				else{
					v*=10;
					v+=c-'0';
				}
			}
			else{
				if(c=='.')abort;
				v+=(c-'0')*f;
				f/=10;
			}
			c=getchar();
		}
		ungetc(c,stdin);
		yylval=v;
		return NUM;
	}
	abort();
}

结果却报错,warning: rule useless in grammar [-Wother]

经过

经过<3!=6次尝试调整lines,line,expr的位置关系,最终发现,当lines作为第一条时,不会报错.并且不论顺序如何,只要在声明部分加上%start lines也不会报错.

结果

所以我猜测,如果没有%start声明,bison会把第一条生成规则作为start rule

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值