Repository navigation
Expand file tree
/
Copy pathOracle.java
More file actions
260 lines (245 loc) · 12.1 KB
/
Copy pathOracle.java
File metadata and controls
260 lines (245 loc) · 12.1 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
// Authoritative Java structure oracle for the cgr eval harness.
//
// Parses every .java file under a directory with the JDK's own Compiler Tree API
// (javax.tools + com.sun.source) and emits one JSON record per declaration, in
// cgr's NodeLabel vocabulary, so records join cgr's graph on (kind, file, line).
// task.parse() only parses (no resolution), so missing dependencies are fine.
//
// Mapping (Java construct -> cgr NodeLabel):
//
// class -> Class
// interface / @interface -> Interface (its method signatures -> Method)
// enum -> Enum
// method / constructor -> Method
//
// Containment edges (matching how cgr models Java containment):
//
// DEFINES : the file module -> every named type (top-level OR nested)
// DEFINES_METHOD : the method's immediate enclosing named type -> Method
//
// cgr models a Java module per file (keyed at line 0) and DEFINES every named
// type from it (containment is flat, not nested-type-scoped). A method binds to
// its nearest enclosing named type. Methods of an anonymous class are Functions
// (no DEFINES_METHOD), matching the node mapping.
//
// Output is a {nodes, edges} payload joining cgr on (kind, file, line).
//
// Compile: javac Oracle.java ; Run: java -cp <dir> Oracle <dir>
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.LineMap;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class Oracle {
static final Set<String> IGNORED =
new HashSet<>(Arrays.asList(".git", "target", "build", "node_modules", "vendor"));
static final List<String> recs = new ArrayList<>();
static final List<String> edges = new ArrayList<>();
static final List<String> nameEdges = new ArrayList<>();
static final List<String> calls = new ArrayList<>();
static final long MODULE_LINE = 0;
static String esc(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"");
}
// Simple name of an extends/implements type: drop generics and any
// package/outer qualifier, matching how cgr resolves bases by simple name.
static String simpleName(Object typeTree) {
String s = typeTree.toString();
int lt = s.indexOf('<');
if (lt >= 0) {
s = s.substring(0, lt);
}
int dot = s.lastIndexOf('.');
if (dot >= 0) {
s = s.substring(dot + 1);
}
return s.trim();
}
static void emitNameEdge(
String rel, String file, String skind, long sline, String targetName) {
nameEdges.add("{\"rel\":\"" + rel + "\",\"source\":{\"kind\":\"" + skind
+ "\",\"file\":\"" + esc(file) + "\",\"line\":" + sline
+ "},\"target_name\":\"" + esc(targetName) + "\"}");
}
// A file-level call site: caller file + callee simple name (the method
// identifier). The Python side keeps only callees whose name is a declared
// first-party Method/Function, mirroring the Go/Rust call oracles.
static void emitCall(String file, String name) {
calls.add("{\"file\":\"" + esc(file) + "\",\"name\":\"" + esc(name) + "\"}");
}
static void emit(String kind, String file, long line, long endLine, String name) {
recs.add("{\"kind\":\"" + kind + "\",\"file\":\"" + esc(file)
+ "\",\"line\":" + line + ",\"end_line\":" + endLine
+ ",\"name\":\"" + esc(name) + "\"}");
}
static void emitEdge(
String rel, String file, String pkind, long pline, String ckind, long cline) {
edges.add("{\"rel\":\"" + rel + "\",\"parent\":{\"kind\":\"" + pkind
+ "\",\"file\":\"" + esc(file) + "\",\"line\":" + pline
+ "},\"child\":{\"kind\":\"" + ckind + "\",\"file\":\"" + esc(file)
+ "\",\"line\":" + cline + "}}");
}
static String classKind(ClassTree node) {
switch (node.getKind()) {
case INTERFACE:
return "Interface";
case ENUM:
return "Enum";
// cgr models an annotation type (@interface) as a Class.
default:
return "Class";
}
}
public static void main(String[] args) throws Exception {
Path root = Paths.get(args[0]).toAbsolutePath().normalize();
List<Path> files = new ArrayList<>();
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
public FileVisitResult preVisitDirectory(Path d, BasicFileAttributes a) {
Path name = d.getFileName();
if (name != null && IGNORED.contains(name.toString())) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
public FileVisitResult visitFile(Path f, BasicFileAttributes a) {
if (f.toString().endsWith(".java")) {
files.add(f);
}
return FileVisitResult.CONTINUE;
}
});
if (files.isEmpty()) {
System.out.print("{\"nodes\":[],\"edges\":[],\"name_edges\":[]}");
return;
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
Iterable<? extends JavaFileObject> units = fm.getJavaFileObjectsFromPaths(files);
JavacTask task = (JavacTask) compiler.getTask(null, fm, d -> {}, null, null, units);
SourcePositions sp = Trees.instance(task).getSourcePositions();
for (CompilationUnitTree unit : task.parse()) {
Path abs = Paths.get(unit.getSourceFile().toUri());
String rel = root.relativize(abs).toString().replace('\\', '/');
LineMap lm = unit.getLineMap();
new TreePathScanner<Void, Void>() {
public Void visitClass(ClassTree node, Void p) {
long pos = sp.getStartPosition(unit, node);
// Anonymous classes have an empty name and no cgr node.
if (pos >= 0 && node.getSimpleName().length() > 0) {
long line = lm.getLineNumber(pos);
long endLine = lm.getLineNumber(sp.getEndPosition(unit, node));
String kind = classKind(node);
emit(kind, rel, line, endLine, node.getSimpleName().toString());
// Every named type is DEFINEd by the file module,
// including nested types (cgr keeps this flat).
emitEdge("DEFINES", rel, "Module", MODULE_LINE, kind, line);
// extends superclass -> INHERITS (a class only).
if (node.getExtendsClause() != null) {
emitNameEdge("INHERITS", rel, kind, line,
simpleName(node.getExtendsClause()));
}
// The implements clause holds a class/enum's interfaces
// (-> IMPLEMENTS) but an interface's superinterfaces
// (-> INHERITS, like cgr).
String hrel = node.getKind() == Tree.Kind.INTERFACE
? "INHERITS" : "IMPLEMENTS";
for (Tree it : node.getImplementsClause()) {
emitNameEdge(hrel, rel, kind, line, simpleName(it));
}
}
return super.visitClass(node, p);
}
public Void visitMethod(MethodTree node, Void p) {
long pos = sp.getStartPosition(unit, node);
if (pos >= 0) {
// cgr labels a member a Method only when its nearest
// enclosing named class precedes any enclosing method or
// lambda body; members of an anonymous class (declared in
// a method body) are modelled as standalone Functions.
String kind = "Function";
ClassTree owner = null;
for (TreePath up = getCurrentPath().getParentPath();
up != null; up = up.getParentPath()) {
Tree t = up.getLeaf();
if (t instanceof ClassTree
&& ((ClassTree) t).getSimpleName().length() > 0) {
kind = "Method";
owner = (ClassTree) t;
break;
}
if (t instanceof MethodTree || t instanceof LambdaExpressionTree) {
break;
}
}
long line = lm.getLineNumber(pos);
long endLine = lm.getLineNumber(sp.getEndPosition(unit, node));
emit(kind, rel, line, endLine, node.getName().toString());
// A Method binds to its enclosing named type; an
// anonymous-class member (Function) has no owner node,
// so cgr anchors it to the module with DEFINES (the
// orphan-prevention fallback) and the oracle models
// the same containment.
if (owner != null) {
long opos = sp.getStartPosition(unit, owner);
if (opos >= 0) {
emitEdge("DEFINES_METHOD", rel, classKind(owner),
lm.getLineNumber(opos), "Method", line);
}
} else {
emitEdge("DEFINES", rel, "Module", MODULE_LINE,
"Function", line);
}
}
return super.visitMethod(node, p);
}
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
// The callee simple name: the trailing identifier of a
// member-select (`obj.foo()`, `Type.bar()`) or a bare
// identifier (`foo()`, same-class or static-imported). A
// `super()`/`this()` constructor call yields "super"/"this"
// and is dropped downstream (never a declared method name).
ExpressionTree sel = node.getMethodSelect();
String name = null;
if (sel instanceof MemberSelectTree) {
name = ((MemberSelectTree) sel).getIdentifier().toString();
} else if (sel instanceof IdentifierTree) {
name = ((IdentifierTree) sel).getName().toString();
}
if (name != null) {
emitCall(rel, name);
}
return super.visitMethodInvocation(node, p);
}
}.scan(unit, null);
}
System.out.print("{\"nodes\":[" + String.join(",", recs)
+ "],\"edges\":[" + String.join(",", edges)
+ "],\"name_edges\":[" + String.join(",", nameEdges)
+ "],\"calls\":[" + String.join(",", calls) + "]}");
}
}