forked from georgewfraser/java-language-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaCompilerService.java
More file actions
334 lines (302 loc) · 12.4 KB
/
JavaCompilerService.java
File metadata and controls
334 lines (302 loc) · 12.4 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package org.javacs;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.tools.*;
class JavaCompilerService implements CompilerProvider {
// Not modifiable! If you want to edit these, you need to create a new instance
final Set<Path> classPath, docPath;
final Set<String> addExports;
final ReusableCompiler compiler = new ReusableCompiler();
final Docs docs;
final Set<String> jdkClasses = ScanClassPath.jdkTopLevelClasses(), classPathClasses;
// Diagnostics from the last compilation task
final List<Diagnostic<? extends JavaFileObject>> diags = new ArrayList<>();
// Use the same file manager for multiple tasks, so we don't repeatedly re-compile the same files
// TODO intercept files that aren't in the batch and erase method bodies so compilation is faster
final SourceFileManager fileManager;
JavaCompilerService(Set<Path> classPath, Set<Path> docPath, Set<String> addExports) {
System.err.println("Class path:");
for (var p : classPath) {
System.err.println(" " + p);
}
System.err.println("Doc path:");
for (var p : docPath) {
System.err.println(" " + p);
}
// classPath can't actually be modified, because JavaCompiler remembers it from task to task
this.classPath = Collections.unmodifiableSet(classPath);
this.docPath = Collections.unmodifiableSet(docPath);
this.addExports = Collections.unmodifiableSet(addExports);
this.docs = new Docs(docPath);
this.classPathClasses = ScanClassPath.classPathTopLevelClasses(classPath);
this.fileManager = new SourceFileManager();
}
private CompileBatch cachedCompile;
private Map<JavaFileObject, Long> cachedModified = new HashMap<>();
private boolean needsCompile(Collection<? extends JavaFileObject> sources) {
if (cachedModified.size() != sources.size()) {
return true;
}
for (var f : sources) {
if (!cachedModified.containsKey(f)) {
return true;
}
if (f.getLastModified() != cachedModified.get(f)) {
return true;
}
}
return false;
}
private void loadCompile(Collection<? extends JavaFileObject> sources) {
if (cachedCompile != null) {
if (!cachedCompile.closed) {
throw new RuntimeException("Compiler is still in-use!");
}
cachedCompile.borrow.close();
}
cachedCompile = doCompile(sources);
cachedModified.clear();
for (var f : sources) {
cachedModified.put(f, f.getLastModified());
}
}
private CompileBatch doCompile(Collection<? extends JavaFileObject> sources) {
if (sources.isEmpty()) throw new RuntimeException("empty sources");
var firstAttempt = new CompileBatch(this, sources);
var addFiles = firstAttempt.needsAdditionalSources();
if (addFiles.isEmpty()) return firstAttempt;
// If the compiler needs additional source files that contain package-private files
LOG.info("...need to recompile with " + addFiles);
firstAttempt.close();
firstAttempt.borrow.close();
var moreSources = new ArrayList<JavaFileObject>();
moreSources.addAll(sources);
for (var add : addFiles) {
moreSources.add(new SourceFileObject(add));
}
return new CompileBatch(this, moreSources);
}
private CompileBatch compileBatch(Collection<? extends JavaFileObject> sources) {
if (needsCompile(sources)) {
loadCompile(sources);
} else {
LOG.info("...using cached compile");
}
return cachedCompile;
}
private static final Cache<String, Boolean> cacheContainsWord = new Cache<>();
private boolean containsWord(Path file, String word) {
if (cacheContainsWord.needs(file, word)) {
cacheContainsWord.load(file, word, StringSearch.containsWord(file, word));
}
return cacheContainsWord.get(file, word);
}
private static final Cache<Void, List<String>> cacheContainsType = new Cache<>();
private boolean containsType(Path file, String className) {
if (cacheContainsType.needs(file, null)) {
var root = parse(file).root;
var types = new ArrayList<String>();
new FindTypeDeclarations().scan(root, types);
cacheContainsType.load(file, null, types);
}
return cacheContainsType.get(file, null).contains(className);
}
private Cache<Void, List<String>> cacheFileImports = new Cache<>();
private List<String> readImports(Path file) {
if (cacheFileImports.needs(file, null)) {
loadImports(file);
}
return cacheFileImports.get(file, null);
}
private void loadImports(Path file) {
var list = new ArrayList<String>();
var importClass = Pattern.compile("^import +([\\w\\.]+\\.\\w+);");
var importStar = Pattern.compile("^import +([\\w\\.]+\\.\\*);");
try (var lines = FileStore.lines(file)) {
for (var line = lines.readLine(); line != null; line = lines.readLine()) {
// If we reach a class declaration, stop looking for imports
// TODO This could be a little more specific
if (line.contains("class")) break;
// import foo.bar.Doh;
var matchesClass = importClass.matcher(line);
if (matchesClass.matches()) {
list.add(matchesClass.group(1));
}
// import foo.bar.*
var matchesStar = importStar.matcher(line);
if (matchesStar.matches()) {
list.add(matchesStar.group(1));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
cacheFileImports.load(file, null, list);
}
@Override
public Set<String> imports() {
var all = new HashSet<String>();
for (var f : FileStore.all()) {
all.addAll(readImports(f));
}
return all;
}
@Override
public List<String> publicTopLevelTypes() {
var all = new ArrayList<String>();
for (var file : FileStore.all()) {
var fileName = file.getFileName().toString();
if (!fileName.endsWith(".java")) continue;
var className = fileName.substring(0, fileName.length() - ".java".length());
var packageName = FileStore.packageName(file);
if (!packageName.isEmpty()) {
className = packageName + "." + className;
}
all.add(className);
}
all.addAll(classPathClasses);
all.addAll(jdkClasses);
return all;
}
@Override
public List<String> packagePrivateTopLevelTypes(String packageName) {
return List.of("TODO");
}
private boolean containsImport(Path file, String className) {
var packageName = Extractors.packageName(className);
if (FileStore.packageName(file).equals(packageName)) return true;
var star = packageName + ".*";
for (var i : readImports(file)) {
if (i.equals(className) || i.equals(star)) return true;
}
return false;
}
@Override
public Iterable<Path> search(String query) {
Predicate<Path> test = f -> StringSearch.containsWordMatching(f, query);
return () -> FileStore.all().stream().filter(test).iterator();
}
@Override
public Optional<JavaFileObject> findAnywhere(String className) {
var fromDocs = findPublicTypeDeclarationInDocPath(className);
if (fromDocs.isPresent()) {
return fromDocs;
}
var fromJdk = findPublicTypeDeclarationInJdk(className);
if (fromJdk.isPresent()) {
return fromJdk;
}
var fromSource = findTypeDeclaration(className);
if (fromSource != NOT_FOUND) {
return Optional.of(new SourceFileObject(fromSource));
}
return Optional.empty();
}
private Optional<JavaFileObject> findPublicTypeDeclarationInDocPath(String className) {
try {
var found =
docs.fileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH, className, JavaFileObject.Kind.SOURCE);
return Optional.ofNullable(found);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Optional<JavaFileObject> findPublicTypeDeclarationInJdk(String className) {
try {
for (var module : ScanClassPath.JDK_MODULES) {
var moduleLocation = docs.fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, module);
if (moduleLocation == null) continue;
var fromModuleSourcePath =
docs.fileManager.getJavaFileForInput(moduleLocation, className, JavaFileObject.Kind.SOURCE);
if (fromModuleSourcePath != null) {
LOG.info(String.format("...found %s in module %s of jdk", fromModuleSourcePath.toUri(), module));
return Optional.of(fromModuleSourcePath);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return Optional.empty();
}
@Override
public Path findTypeDeclaration(String className) {
var fastFind = findPublicTypeDeclaration(className);
if (fastFind != NOT_FOUND) return fastFind;
// In principle, the slow path can be skipped in many cases.
// If we're spending a lot of time in findTypeDeclaration, this would be a good optimization.
var packageName = Extractors.packageName(className);
var simpleName = Extractors.simpleName(className);
for (var f : FileStore.list(packageName)) {
if (containsWord(f, simpleName) && containsType(f, className)) {
return f;
}
}
return NOT_FOUND;
}
private Path findPublicTypeDeclaration(String className) {
JavaFileObject source;
try {
source =
fileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH, className, JavaFileObject.Kind.SOURCE);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (source == null) return NOT_FOUND;
if (!source.toUri().getScheme().equals("file")) return NOT_FOUND;
var file = Paths.get(source.toUri());
if (!containsType(file, className)) return NOT_FOUND;
return file;
}
@Override
public Path[] findTypeReferences(String className) {
var packageName = Extractors.packageName(className);
var simpleName = Extractors.simpleName(className);
var candidates = new ArrayList<Path>();
for (var f : FileStore.all()) {
if (containsWord(f, packageName) && containsImport(f, className) && containsWord(f, simpleName)) {
candidates.add(f);
}
}
return candidates.toArray(Path[]::new);
}
@Override
public Path[] findMemberReferences(String className, String memberName) {
var candidates = new ArrayList<Path>();
for (var f : FileStore.all()) {
if (containsWord(f, memberName)) {
candidates.add(f);
}
}
return candidates.toArray(Path[]::new);
}
@Override
public ParseTask parse(Path file) {
var parser = Parser.parseFile(file);
return new ParseTask(parser.task, parser.root);
}
@Override
public ParseTask parse(JavaFileObject file) {
var parser = Parser.parseJavaFileObject(file);
return new ParseTask(parser.task, parser.root);
}
@Override
public CompileTask compile(Path... files) {
var sources = new ArrayList<JavaFileObject>();
for (var f : files) {
sources.add(new SourceFileObject(f));
}
return compile(sources);
}
@Override
public CompileTask compile(Collection<? extends JavaFileObject> sources) {
var compile = compileBatch(sources);
return new CompileTask(compile.task, compile.roots, diags, compile::close);
}
private static final Logger LOG = Logger.getLogger("main");
}