-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression to TAC.cpp
More file actions
114 lines (97 loc) · 2.88 KB
/
Copy pathexpression to TAC.cpp
File metadata and controls
114 lines (97 loc) · 2.88 KB
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
#include <bits/stdc++.h>
using namespace std;
string code = "a + b + c * d / e - f";
// string code = "( a + b ) * ( c / e )";
vector<string> ans;
vector<string> tok;
stack<string> st;
int cnt1 = 0, cnt2 = 0;
void tokenize() {
string s;
stringstream ss(code);
while (ss >> s) {
tok.push_back(s);
}
}
int pre(string s) {
if (s == "+" || s == "-") {
return 1;
} else if (s == "*" || s == "/") {
return 2;
} else {
return -1;
}
}
void postfix() {
for (int i = 0; i < tok.size(); i++) {
if (tok[i] == "+" || tok[i] == "-" || tok[i] == "*" || tok[i] == "/") {
while (!st.empty() && pre(st.top()) >= pre(tok[i])) {
ans.push_back(st.top());
st.pop();
}
st.push(tok[i]);
} else if (tok[i] == "(") {
st.push(tok[i]);
} else if (tok[i] == ")") {
while (!st.empty() && st.top() != "(") {
ans.push_back(st.top());
st.pop();
}
st.pop(); // pop "("
} else {
ans.push_back(tok[i]);
}
}
while (!st.empty()) {
ans.push_back(st.top());
st.pop();
}
}
// Generate unique temp variable t0, t1, ...
string t() {
return "t" + to_string(cnt1++);
}
// Generate unique register R0, R1, ...
string R() {
return "R" + to_string(cnt2++);
}
// Replace tokens from [start, end] with temp variable
void replace(int start, int end, string temp) {
ans.erase(ans.begin() + start, ans.begin() + end + 1);
ans.insert(ans.begin() + start, temp);
}
// Generate three-address code and assembly-like instructions
void g3ac() {
int i = 0;
while (i < ans.size()) {
string p1, p2, op, tmp;
if (ans[i] == "+" || ans[i] == "-" || ans[i] == "*" || ans[i] == "/") {
p1 = ans[i - 2];
p2 = ans[i - 1];
op = ans[i];
tmp = t();
cout << tmp << " = " << p1 << " " << op << " " << p2 << endl;
string r = R();
cout << "MOV " << r << ", " << p1 << endl;
if (op == "+") cout << "ADD " << r << ", " << p2 << endl;
if (op == "-") cout << "SUB " << r << ", " << p2 << endl;
if (op == "*") cout << "MUL " << r << ", " << p2 << endl;
if (op == "/") cout << "DIV " << r << ", " << p2 << endl;
replace(i - 2, i, tmp);
i = 0; // Reset i to re-scan new list with temp variable
} else {
i++;
}
}
}
int main() {
tokenize();
postfix();
cout << "Postfix Expression: ";
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl << endl;
cout << "Three Address Code and Assembly Instructions:\n";
g3ac();
}