Repository navigation
Expand file tree
/
Copy pathCM.java
More file actions
114 lines (94 loc) · 2.85 KB
/
Copy pathCM.java
File metadata and controls
114 lines (94 loc) · 2.85 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
import absyn.*;
import symbol.Log;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintStream;
public class CM {
private static final int FLAG_A = 1, FLAG_S = 2, FLAG_C = 4;
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: CM [-a] [-s] <filename>.cm");
return;
}
int flags = 0;
String filename = null;
// Read file
for (String arg : args) {
if (arg.equals("-a")) {
flags |= FLAG_A;
} else if (arg.equals("-s")) {
flags |= FLAG_S;
} else if (arg.equals("-c")) {
flags |= FLAG_C;
} else if (arg.toLowerCase().endsWith(".cm")) {
filename = arg;
}
}
if (filename == null) {
System.out.println("Require a file ending in \".cm\"");
return;
}
Parser parser;
List<?> result;
try {
parser = new Parser(new Lexer(new FileReader(filename)));
result = (List<?>)(parser.parse().value);
} catch (Exception e) {
Log.critical("Error when parsing: " + e.getMessage());
e.printStackTrace();
return;
};
String outfile = filename.substring(0, filename.length() - 3);
if ((flags & FLAG_A) != 0) {
printAST(outfile + ".ast", result);
}
// Work analyzer
SemanticAnalyzer analyzer;
try {
analyzer = new SemanticAnalyzer();
result.accept(analyzer, 0, false);
} catch (Exception e) {
Log.critical("ERROR WITH SYMANTICS: " + e.getMessage());
e.printStackTrace();
return;
}
if ((flags & FLAG_S) != 0) {
symantic(outfile + ".sym", analyzer, result);
}
if ((flags & FLAG_C) != 0) {
if (Log.getErrorCount() > 0) {
System.err.println("Cannot compile, must fix " + Log.getErrorCount() + " errors");
} else {
compile(outfile + ".tm", analyzer, result);
}
}
}
private static void printAST(String outfile, List<?> result) {
try {
if (result != null) {
PrintStream stream = new PrintStream(outfile);
AbsynVisitor visitor = new ShowTreeVisitor(stream);
result.accept(visitor, 0, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void symantic(String outfile, SemanticAnalyzer analyzer, List<?> result) {
try {
PrintStream stream = new PrintStream(outfile);
analyzer.getGlobalScope().print(stream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void compile(String outfile, SemanticAnalyzer analyzer, List<?> result) {
try {
PrintStream stream = new PrintStream(outfile);
CodeGenerator generator = new CodeGenerator(stream, analyzer.getGlobalScope(), result);
} catch (Exception e) {
Log.critical("Something went wrong with compiler:");
e.printStackTrace();
}
}
}