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

猜你喜欢

转载自blog.csdn.net/agctXY/article/details/117291329