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