Program for implementing a calculator for computing the given expression using semantic rules of the YACC tool


  1. A Yacc source program has three parts as follows:



translation rules


supporting C routines

  1. Declarations Section:

This section contains entries that:

  1. Include standard I/O header file.
  2. Define global variables.
  • Define the list rule as the place to start processing.
  1. Define the tokens used by the parser.
  2. Define the operators and their precedence.
  1. Rules Section: The rules section defines the rules that parse the input stream. Each rule of a grammar  production and the associated semantic action.
  1. Programs Section: The programs section contains the following subroutines. Because these subroutines are included in this file, it is not necessary to use the yacc  library when processing this file.
  1. Main- The required main program that calls the yyparse subroutine to start the program.
  2. yyerror(s) -This error-handling subroutine only prints a syntax error message.
  3. yywrap -The wrap-up subroutine that returns a value of 1 when the end of input occurs. The calc.lex file contains include statements for standard input and output, as programmar file information if we use the -d flag with the yacc command. The file contains definitions for the tokens that the parser program uses.
  4. lex contains the rules to generate these tokens from the input stream.



([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {
return NUMBER;}
MEM {return MEM;}
\$ {return 0;}
\n {return yytext[0];}
. {return yytext[0];}



double memvar;

double dval;
%token NUMBER
%token MEM
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%type expression
start:statement '\n'
|start statement '\n'
statement:MEM '=' expression {memvar=$3;}
|expression {printf("answer=%g\n",$1);}
expression:expression'+'expression {$$=$1+$3;}
|expression'-'expression {$$=$1-$3;}
|expression'*'expression {$$=$1*$3;}
|expression'/'expression {if($3==0)
yyerror("divide by zero");
expression:'-'expression %prec UMINUS {$$= -$2;}
|'('expression')' {$$=$2;}
|NUMBER {$$=$1;}
|MEM {$$=memvar;};


int main(void)
printf("Enter the expression");
return 0;

int yywrap()
return 0;

int yyerror(char *error)
return 0;

[CSE@localhost ~]$ lex cal.l

[CSE@localhost ~]$ yacc -d cal.y

[CSE@localhost ~]$ cc lex.yy.c -ll

[CSE@localhost ~]$ ./a.out

Enter the expression5+3


[cse@NFSSERVER ~]$ ./a.out

Enter the expression5+-5


[cse@NFSSERVER ~]$ ./a.out

Enter the expression+5/

syntax error

Leave a Reply