aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/makamys/neodymium/util/Preprocessor.java
blob: 8ee9229549dc9d678ab06ae037fc6a0841f6d58a (plain)
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
package makamys.neodymium.util;

import java.util.Set;

public class Preprocessor {
    
    public static String preprocess(String text, Set<String> defines) {
        String[] lines = text.replaceAll("\\r\\n", "\\n").split("\\n");
        
        IfElseBlockStatus ifElseBlockStatus = IfElseBlockStatus.NONE;
        boolean ifElseConditionMet = false;
        
        for(int i = 0; i < lines.length; i++) {
            String line = lines[i];
            
            boolean commentLine = false;
            
            if(line.startsWith("#ifdef ")) {
                ifElseBlockStatus = IfElseBlockStatus.IF;
                ifElseConditionMet = defines.contains(line.split(" ")[1]);
                commentLine = true;
            } else if(line.startsWith("#else")) {
                ifElseBlockStatus = IfElseBlockStatus.ELSE;
                commentLine = true;
            } else if(line.startsWith("#endif")) {
                ifElseBlockStatus = IfElseBlockStatus.NONE;
                commentLine = true;
            } else {
                if(ifElseBlockStatus == IfElseBlockStatus.IF && !ifElseConditionMet) {
                    commentLine = true;
                }
                if(ifElseBlockStatus == IfElseBlockStatus.ELSE && ifElseConditionMet) {
                    commentLine = true;
                }
            }
            
            if(commentLine) {
                lines[i] = "//" + line;
            }
        }
        
        return String.join("\n", lines);
    }
    
    public static enum IfElseBlockStatus {
        NONE, IF, ELSE;
    }
    
}