Iam trying to develop a program for a calculator using lex and yacc. I keeping getting the following error:
calc.y: warning: 5 nonterminals useless in grammar [-Wother]
calc.y: warning: 8 rules useless in grammar [-Wother]
calc.y:8.1: fatal error: start symbol I does not derive any sentence
I : E '\n' {printf("%d\n",$1);}
I looked at similiar problems but they had infinite recursions but this one doesn't have .
calc.l
%{
#include"y.tab.h"
%}
digits [0-9]*
%%
{digits} {return DIGITS}
%%
int yywrap()
{
}
calc.y
%{
#include<stdio.h>
%}
%token DIGITS
%%
I : E '\n' {printf("%d\n",$1);}
;
E : E '+' F {$$ = $1 + $3;}
| E '-' F {$$ = $1 - $3;}
;
F : F '*' G {$$ = $1 * $3;}
| F '/' G {$$ = $1 / $3;}
G :'('E')'
| DIGITS
;
%%
int main()
{
yyparse();
}
int yyerror()
{
}
I don't know yacc, but:
To build an I
, you need an E
:
I : E '\n'
To build an E
, you need an E
:
E : E '+' F
| E '-' F
Since there is no way to build an E
if you don't already have one (and in the beginning you don't have anything), there is no way to build an I
either.
Or looking at it from the other side: E
is infinitely recursive because it always refers back to itself.
If we start with the lexer, we get DIGITS
first.
DIGITS
can be used to build a G
.
But there's nothing we can do with a G
because the only rules that use it (F '*' G
and F '/' G
) also require an F
to proceed, and we don't have an F
. So we're stuck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With