-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprg4.txt
84 lines (81 loc) · 2.3 KB
/
prg4.txt
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
.l part
%{
/* Design, develop and implement YACC/C program to demonstrate Shift Reduce Parsing technique for
the grammar rules: E →E+T | T, T →T*F | F, F → (E) | id and parse the sentence: id + id * id. */
#include "y.tab.h"
char stack[20];
char in[20];
int st_ptr=0;
int ip_ptr=0;
%}
%%
[a-z]+ {stack[++st_ptr]='i';stack[++st_ptr]='d';in[ip_ptr++]=' '; in[ip_ptr++]=' ';printf("%s\t%s\tshift id\n",stack,in); return id;}
[ \t] ;
[+] { return yytext[0];}
[*] {return yytext[0];}
[(] {return yytext[0];}
[)] {return yytext[0];}
. ;
\n return 0;
%%
.y part
%{
#include<stdio.h>
#include<stdlib.h>
extern char stack[];
extern char in[];
extern int st_ptr;
extern int ip_ptr;
extern FILE *yyin;
%}
%token id
%%
e:e'+' {stack[++st_ptr]='+';
in[ip_ptr++]=' ';
printf("%s\t%s\tshift +\n",stack,in);} t {stack[st_ptr--]=' ';
stack[st_ptr--]=' ';
printf("%s\t%s\treduce e->e+t\n",stack,in);}
|t {stack[st_ptr]='e';
printf("%s\t%s\treduce e->t\n",stack,in);}
t:t'*' {stack[++st_ptr]='*';
in[ip_ptr++]=' ';
printf("%s\t%s\tshift *\n",stack,in);} f {stack[st_ptr--]=' ';
stack[st_ptr--]=' ';
printf("%s\t%s\treduce t->t*f\n",stack,in);}
|f {stack[st_ptr]='t';
printf("%s\t%s\treduce t->f\n",stack,in);}
f:'(' {stack[++st_ptr]='(';
in[ip_ptr++]=' ';
printf("%s\t%s\tshift (\n",stack,in);} e')' {stack[++st_ptr]=')';
in[ip_ptr++]=' ';
printf("%s\t%s\tshift )\n",stack,in);
stack[st_ptr--]=' ';
stack[st_ptr--]=' ';
stack[st_ptr]='f';
printf("%s\t%s\treduced f->(e)\n",stack,in);}
|id {stack[st_ptr--]=' ';
stack[st_ptr]='f';
printf("%s\t%s\treduce f->id\n",stack,in);}
;
%%
main(int argc,char *argv[])
{
stack[ip_ptr]='$';
FILE *fp1;
fp1=fopen(argv[1],"r");
while(!feof(fp1))
fscanf(fp1,"%s",in);
fclose(fp1);
yyin=fopen(argv[1],"r");
printf("stack\tinput\taction\n");
while(!feof(yyin))
{
if(!yyparse())
printf("\nValid simple exp \n");
}
}
yyerror()
{
printf("\nInvalid simple expression \n");
exit(0);
}