-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpreprocessor.js
69 lines (60 loc) · 2.17 KB
/
preprocessor.js
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
function preprocessJavaScript(sourceCode, defines = {}) {
const lines = sourceCode.split('\n');
const output = [];
const ifdefStack = [];
const elseStack = []; // Track whether we've seen an #else for each level
let currentlyIncluding = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Handle #ifdef directive
if (line.startsWith('#ifdef')) {
const symbol = line.split(' ')[1];
const conditionResult = defines[symbol] === true;
ifdefStack.push(currentlyIncluding);
elseStack.push(false); // Haven't seen an #else yet for this level
currentlyIncluding = currentlyIncluding && conditionResult;
continue;
}
// Handle #ifndef directive
if (line.startsWith('#ifndef')) {
const symbol = line.split(' ')[1];
const conditionResult = defines[symbol] !== true;
ifdefStack.push(currentlyIncluding);
elseStack.push(false); // Haven't seen an #else yet for this level
currentlyIncluding = currentlyIncluding && conditionResult;
continue;
}
// Handle #else directive
if (line === '#else' || line.startsWith('#else ')) {
if (ifdefStack.length === 0) {
throw new Error(`Unmatched #else at line ${i + 1}`);
}
if (elseStack[elseStack.length - 1]) {
throw new Error(`Multiple #else directives for the same #if* at line ${i + 1}`);
}
elseStack[elseStack.length - 1] = true;
const parentIncluding = ifdefStack[ifdefStack.length - 1];
currentlyIncluding = parentIncluding && !currentlyIncluding;
continue;
}
// Handle #endif directive
if (line === '#endif' || line.startsWith('#endif ')) {
if (ifdefStack.length === 0) {
throw new Error(`Unmatched #endif at line ${i + 1}`);
}
currentlyIncluding = ifdefStack.pop();
elseStack.pop();
continue;
}
// Include the line if we're in an active branch
if (currentlyIncluding) {
output.push(lines[i]);
}
}
// Check for unmatched #ifdef/#ifndef
if (ifdefStack.length > 0) {
throw new Error('Unmatched #ifdef or #ifndef directive');
}
return output.join('\n');
}
export { preprocessJavaScript };