blob: 37de2200501683d845a38ced3eb48e50f43cc7b2 (
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
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
|
package com.clp.project;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import javax.swing.*;
import org.antlr.v4.gui.TreeViewer;
import org.antlr.v4.runtime.*;
import com.clp.project.parser.*;
public class ParseAll {
public static void main(String[] args) {
new File("./trees/").mkdirs();
for (File file : Objects.requireNonNull(new File("./progs").listFiles())) {
String fileStr = file.getPath();
// fileStr = "./progs/wrong.py";
try {
if (!file.isFile() || !getExtension(file.getName()).equals("py")) {
System.err.println("Wont parse: " + fileStr);
continue;
} else {
System.out.println(fileStr);
}
// System.out.println(readFile(fileStr));
CharStream cs = CharStreams.fromFileName(fileStr);
Python3Lexer lexer = new Python3Lexer(cs);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
Python3Parser parser = new Python3Parser(tokenStream);
Python3Parser.RootContext tree = parser.root();
String treeStr = tree.toStringTree();
// System.out.println(treeStr);
TreeViewer viewer = new TreeViewer(Arrays.asList(parser.getRuleNames()), tree);
viewer.setScale(1.5);
saveTree(viewer, "./trees/" + removeExtension(file.getName()) + ".png");
if (parser.getNumberOfSyntaxErrors() != 0) {
System.err.println("Parse errors: " + fileStr);
}
} catch (Exception e) {
e.printStackTrace();
System.err.println(fileStr);
}
}
}
private static String readFile(String filePath) throws IOException {
StringBuilder content = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
}
return content.toString();
}
private static void showTree(TreeViewer viewer) {
JFrame frame = new JFrame("Parse Tree");
JPanel panel = new JPanel();
panel.add(viewer);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
private static void saveTree(TreeViewer viewer, String name) {
try {
viewer.save(name);
} catch (Exception e) {
System.err.println(name);
e.printStackTrace();
}
}
public static String removeExtension(String fileName) {
int extensionIndex = fileName.lastIndexOf('.');
if (extensionIndex == -1) {
return fileName;
} else {
return fileName.substring(0, extensionIndex);
}
}
public static String getExtension(String fileName) {
int extensionIndex = fileName.lastIndexOf('.');
if (extensionIndex == -1) {
return fileName;
} else {
return fileName.substring(extensionIndex + 1);
}
}
}
|