-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathicg.c
130 lines (114 loc) · 3.2 KB
/
icg.c
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int i=1, j=0, no=0, tmpch=90;
char str[100], left[15], right[15];
void findopr();
void explore();
void fleft(int);
void fright(int);
struct exp {
int pos;
char op;
int isUnary;
} k[15];
void main() {
printf("\t\tINTERMEDIATE CODE GENERATION\n\n");
printf("Enter the Expression : ");
scanf("%s", str);
printf("The intermediate code:\n");
findopr();
explore();
}
void findopr() {
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == '(' || str[i] == ')') {
k[j].pos = i;
k[j].isUnary=0;
k[j++].op = str[i];
}
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == '-' && (i == 0 || (str[i-1] == '(' || str[i-1] == '+' || str[i-1] == '-' || str[i-1] == '*' || str[i-1] == '/'))) {
k[j].pos = i;
k[j].isUnary=1;
k[j++].op = '-';
}
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == '/' || str[i] == '*') {
k[j].pos = i;
k[j].isUnary=0;
k[j++].op = str[i];
}
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == '+') {
k[j].pos = i;
k[j].isUnary=0;
k[j++].op = '+';
}
}
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == '-') {
if (i == 0 || (str[i-1] == '(' || str[i-1] == '+' || str[i-1] == '-' || str[i-1] == '*' || str[i-1] == '/')) {
// Unary minus detected (after '(', '+', '-', '*', or '/')
continue;
}
k[j].pos = i;
k[j].isUnary=0;
k[j++].op = '-';
}
}
}
void explore() {
i = 0;
while (k[i].op != '\0') {
if (k[i].op == '(' || k[i].op == ')') {
// Skip parentheses
i++;
continue;
}
if (k[i].isUnary) {
fright(k[i].pos);
str[k[i].pos] = tmpch--;
printf("\t%c := %c %s\t\t", str[k[i].pos], k[i].op, right);
}
else{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos] = tmpch--; // Replace the operator with temporary variable
// Print intermediate code
printf("\t%c := %s %c %s\t\t", str[k[i].pos], left, k[i].op, right);
}
printf("\n");
i++;
}
fright(-1);
}
void fleft(int x) {
int w = 0, flag = 0;
x--;
while (x != -1 && str[x] != '+' && str[x] != '*' && str[x] != '=' && str[x] != '\0' && str[x] != '-' && str[x] != '/' && str[x] != ':') {
if (str[x] != '$' && flag == 0) {
left[w++] = str[x];
left[w] = '\0';
str[x] = '$'; // Mark the operand as processed
flag = 1;
}
x--;
}
}
void fright(int x) {
int w = 0, flag = 0;
x++;
while (x != -1 && str[x] != '+' && str[x] != '*' && str[x] != '\0' && str[x] != '=' && str[x] != '-' && str[x] != '/' && str[x] != ':') {
if (str[x] != '$' && flag == 0) {
right[w++] = str[x];
right[w] = '\0';
str[x] = '$'; // Mark the operand as processed
flag = 1;
}
x++;
}
}