-
Notifications
You must be signed in to change notification settings - Fork 2
/
scal.y
87 lines (67 loc) · 1.14 KB
/
scal.y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
%{
/* Yacc program for a simple calculator */
/*Header files*/
#include<stdio.h>
#include<stdlib.h>
/*Function to calculate power*/
double power(int a, int b);
%}
/*Union for YYSTYPE*/
%union
{
int val;
};
/*Tokens*/
%token <val> NUMBER
%token END
/*Associativity*/
%left '+' '-'
%left '*' '/'
%left '%'
%nonassoc '^'
%nonassoc UMINUS
/*Type of non-terminal*/
%type <val> expr
/*Start variable*/
%start program
%%
program : expr END {
int ans = $1;
printf("\nResult : %d\n",ans);
exit(1);
}
;
expr : expr '+' expr {$$=$1+$3; }
| expr '-' expr {$$=$1-$3; }
| expr '*' expr {$$=$1*$3; }
| expr '/' expr {$$=$1/$3; }
| expr '%' expr {$$=$1%$3; }
| '(' expr ')' {$$=$2; }
| '-' expr %prec UMINUS {$$=-1*$2; }
| expr '^' expr {$$=(int)power($1,$3); }
| NUMBER {$$=$1; }
;
%%
#include "lex.yy.c"
double power(int a,int b)
{
int i;
double c=1;
for(i=0;i<b;i++)
c=c*a;
return c;
}
int yyerror(char *s)
{
fprintf(stderr, "%s in line no : %d\n", s, yylineno);
return 1;
}
int yywrap(void)
{
return 1;
}
int main()
{
yyparse();
return 1;
}