-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
293 lines (247 loc) · 9.73 KB
/
Copy pathapp.js
File metadata and controls
293 lines (247 loc) · 9.73 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
(function () {
'use strict';
// example code
const DEFAULT_CODE = `#include <stdio.h>
int main() {
int a = 5;
int b = 10;
int c = a + b; // used
int d = a * b; // DEAD: d is never used
int e = c + 1; // used in printf
int f = 20; // DEAD: f is never used
int g = a - b; // DEAD: g is never used
if (c > 10) {
int h = c * 2; // used in printf
printf("%d", h);
} else {
int k = 100; // DEAD: k is never used
printf("%d", e);
}
int i = 0;
while (i < 3) {
int temp = i * 2; // used in printf
printf("%d", temp);
i = i + 1;
}
return 0;
}`;
// state
let currentTheme = 'blush';
let lastResult = null;
// DOM Elements
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);
// nitialization
document.addEventListener('DOMContentLoaded', () => {
initTheme();
initTabs();
initActions();
$('#code-input').value = DEFAULT_CODE;
});
// theme management
function initTheme() {
const saved = localStorage.getItem('compiler-theme') || 'blush';
setTheme(saved);
$$('.theme-btn').forEach(btn => {
btn.addEventListener('click', () => {
setTheme(btn.dataset.theme);
});
});
}
function setTheme(theme) {
currentTheme = theme;
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('compiler-theme', theme);
$$('.theme-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.theme === theme);
});
}
// tab management
function initTabs() {
$$('.tab').forEach(tab => {
tab.addEventListener('click', () => {
const target = tab.dataset.tab;
$$('.tab').forEach(t => t.classList.remove('active'));
$$('.tab-content').forEach(c => c.classList.remove('active'));
tab.classList.add('active');
$(`#${target}`).classList.add('active');
});
});
}
// actions
function initActions() {
$('#compile-btn').addEventListener('click', runPipeline);
// allow Ctrl+Enter to compile
$('#code-input').addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'Enter') {
e.preventDefault();
runPipeline();
}
// tab key inserts tab
if (e.key === 'Tab') {
e.preventDefault();
const ta = e.target;
const start = ta.selectionStart;
const end = ta.selectionEnd;
ta.value = ta.value.substring(0, start) + ' ' + ta.value.substring(end);
ta.selectionStart = ta.selectionEnd = start + 4;
}
});
}
// pipeline execution
function runPipeline() {
const source = $('#code-input').value.trim();
if (!source) {
showError('Please enter some C code to compile.');
return;
}
hideError();
showProcessing(true);
// use setTimeout to allow UI to update
setTimeout(() => {
try {
// step 1: lex
const lexer = new Lexer(source);
const tokens = lexer.tokenize();
// step 2: parse
const parser = new Parser(tokens);
const ast = parser.parseProgram();
// step 3: generate 3AC
const tacGen = new TACGenerator();
const originalTAC = tacGen.generate(ast);
const originalLines = TACGenerator.formatInstructions(originalTAC);
// step 4: optimize (dead dode elimination)
const optimizer = new Optimizer();
const optimizedTAC = optimizer.optimize(JSON.parse(JSON.stringify(originalTAC)));
const optimizedLines = TACGenerator.formatInstructions(optimizedTAC);
// find dead lines by comparing
const deadLineIndices = findDeadLines(originalTAC, optimizedTAC);
// step 5: reconstruct (if enabled)
let reconstructedCode = '';
const showReconstruction = $('#reconstruct-toggle').checked;
if (showReconstruction) {
const reconstructor = new Reconstructor();
reconstructedCode = reconstructor.reconstruct(optimizedTAC);
}
// store result
lastResult = {
originalLines,
optimizedLines,
deadLineIndices,
reconstructedCode,
stats: {
originalCount: originalLines.length,
optimizedCount: optimizedLines.length,
eliminated: originalLines.length - optimizedLines.length
}
};
// render
renderOutput();
showProcessing(false);
} catch (e) {
showProcessing(false);
showError(e.message);
}
}, 50);
}
function findDeadLines(original, optimized) {
// create a signature for each optimized instruction
const optimizedSigs = new Set();
const optimizedUsed = [];
for (const instr of optimized) {
optimizedSigs.add(JSON.stringify(instr));
}
// walk through original, marking which are not in optimized
const deadIndices = [];
const tempOptimized = optimized.map(i => JSON.stringify(i));
for (let i = 0; i < original.length; i++) {
const sig = JSON.stringify(original[i]);
const idx = tempOptimized.indexOf(sig);
if (idx === -1) {
deadIndices.push(i);
} else {
// remove from temp to handle duplicates
tempOptimized.splice(idx, 1);
}
}
return deadIndices;
}
// rendering
function renderOutput() {
if (!lastResult) return;
// render original 3AC with dead lines highlighted
renderCodePanel('original-tac', lastResult.originalLines, lastResult.deadLineIndices);
// render optimized 3AC (clean)
renderCodePanel('optimized-tac', lastResult.optimizedLines, []);
// render reconstructed C
const reconstructPanel = $('#reconstructed-c');
const showReconstruction = $('#reconstruct-toggle').checked;
if (showReconstruction && lastResult.reconstructedCode) {
const lines = lastResult.reconstructedCode.split('\n');
renderCodePanel('reconstructed-c', lines, []);
} else {
reconstructPanel.innerHTML = `<div class="placeholder"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-3-3v6m-7 4h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg><span>Enable reconstruction to see C-like output</span></div>`;
}
// update stats
renderStats();
// switch to original TAC tab
$$('.tab')[0].click();
// show the output card with animation
$('.output-panel').classList.add('fade-in');
}
function renderCodePanel(panelId, lines, deadIndices) {
const panel = $(`#${panelId}`);
const deadSet = new Set(deadIndices);
let html = '<div class="code-output">';
for (let i = 0; i < lines.length; i++) {
const isDead = deadSet.has(i);
const lineClass = isDead ? 'line dead' : 'line';
const escapedLine = escapeHtml(lines[i] || ' ');
html += `<span class="${lineClass}"><span class="line-number">${i + 1}</span>${escapedLine}</span>`;
}
html += '</div>';
panel.innerHTML = html;
}
function renderStats() {
if (!lastResult) return;
const s = lastResult.stats;
$('#stat-original').textContent = s.originalCount;
$('#stat-optimized').textContent = s.optimizedCount;
$('#stat-eliminated').textContent = s.eliminated;
const pct = s.originalCount > 0 ? ((s.eliminated / s.originalCount) * 100).toFixed(1) : 0;
$('#stat-reduction').textContent = pct + '%';
}
// error handling
function showError(msg) {
const el = $('#error-display');
el.textContent = '⚠ ' + msg;
el.classList.add('visible');
// clear output panels
['original-tac', 'optimized-tac', 'reconstructed-c'].forEach(id => {
$(`#${id}`).innerHTML = '';
});
}
function hideError() {
$('#error-display').classList.remove('visible');
}
function showProcessing(on) {
const btn = $('#compile-btn');
if (on) {
btn.textContent = 'Compiling...';
btn.classList.add('processing');
btn.disabled = true;
} else {
btn.textContent = 'Compile & Optimize';
btn.classList.remove('processing');
btn.disabled = false;
}
}
// utilities
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
})();