Repository navigation
Expand file tree
/
Copy pathJavadocs.java
More file actions
395 lines (311 loc) · 13.2 KB
/
Copy pathJavadocs.java
File metadata and controls
395 lines (311 loc) · 13.2 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package org.javacs;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonPrimitive;
import com.overzealous.remark.Options;
import com.overzealous.remark.Remark;
import com.sun.javadoc.*;
import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javadoc.api.JavadocTool;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.BreakIterator;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.DocumentationTool;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import org.eclipse.lsp4j.CompletionItem;
public class Javadocs {
/** Cache for performance reasons */
private final JavacFileManager actualFileManager;
/** Empty file manager we pass to javadoc to prevent it from roaming all over the place */
private final JavacFileManager emptyFileManager =
JavacTool.create().getStandardFileManager(JavaLanguageServer::onDiagnostic, null, null);
/** All the classes we have indexed so far */
private final Map<String, IndexedDoc> topLevelClasses = new ConcurrentHashMap<>();
private static class IndexedDoc {
final RootDoc doc;
final Instant updated;
IndexedDoc(RootDoc doc, Instant updated) {
this.doc = doc;
this.updated = updated;
}
}
private final JavacTask task;
private final Function<URI, Optional<String>> activeContent;
Javadocs(
Set<Path> sourcePath,
Set<Path> docPath,
Function<URI, Optional<String>> activeContent) {
this.actualFileManager = createFileManager(allSourcePaths(sourcePath, docPath));
this.task =
JavacTool.create()
.getTask(
null,
emptyFileManager,
JavaLanguageServer::onDiagnostic,
null,
null,
null);
this.activeContent = activeContent;
}
private static Set<File> allSourcePaths(Set<Path>... userSourcePath) {
Set<File> allSourcePaths = new HashSet<>();
// Add userSourcePath
for (Set<Path> eachPath : userSourcePath) {
for (Path each : eachPath) allSourcePaths.add(each.toFile());
}
// Add src.zip from JDK
findSrcZip().ifPresent(allSourcePaths::add);
return allSourcePaths;
}
private static JavacFileManager createFileManager(Set<File> allSourcePaths) {
JavacFileManager actualFileManager =
JavacTool.create()
.getStandardFileManager(JavaLanguageServer::onDiagnostic, null, null);
try {
actualFileManager.setLocation(StandardLocation.SOURCE_PATH, allSourcePaths);
} catch (IOException e) {
throw new RuntimeException(e);
}
return actualFileManager;
}
/** Convert Javadoc HTML to Markdown */
static String htmlToMarkdown(String commentText) {
Options options = new Options();
options.tables = Options.Tables.CONVERT_TO_CODE_BLOCK;
options.hardwraps = true;
options.inlineLinks = true;
options.autoLinks = true;
options.reverseHtmlSmartPunctuation = true;
return new Remark(options).convertFragment(commentText);
}
/** Get docstring for method, using inherited method if necessary */
static Optional<String> commentText(MethodDoc doc) {
// TODO search interfaces as well
while (doc != null && Strings.isNullOrEmpty(doc.commentText()))
doc = doc.overriddenMethod();
if (doc == null || Strings.isNullOrEmpty(doc.commentText())) return Optional.empty();
else return Optional.of(doc.commentText());
}
Optional<? extends ProgramElementDoc> doc(Element el) {
if (el instanceof ExecutableElement) {
ExecutableElement method = (ExecutableElement) el;
return methodDoc(methodKey(method));
} else if (el instanceof TypeElement) {
TypeElement type = (TypeElement) el;
return classDoc(type.getQualifiedName().toString());
} else return Optional.empty();
}
String methodKey(ExecutableElement method) {
TypeElement classElement = (TypeElement) method.getEnclosingElement();
return String.format(
"%s#%s(%s)",
classElement.getQualifiedName(),
method.getSimpleName(),
paramsKey(method.getParameters()));
}
private String paramsKey(List<? extends VariableElement> params) {
return params.stream().map(this::paramType).collect(Collectors.joining(","));
}
Optional<MethodDoc> methodDoc(String methodKey) {
String className = methodKey.substring(0, methodKey.indexOf('#'));
return classDoc(className).flatMap(classDoc -> doMethodDoc(classDoc, methodKey));
}
private Optional<MethodDoc> doMethodDoc(ClassDoc classDoc, String methodKey) {
for (MethodDoc each : classDoc.methods(false)) {
if (methodMatches(methodKey, each)) return Optional.of(each);
}
return Optional.empty();
}
private boolean methodMatches(String methodKey, MethodDoc doc) {
String docKey =
String.format(
"%s#%s(%s)",
doc.containingClass().qualifiedName(),
doc.name(),
paramSignature(doc.parameters()));
return docKey.equals(methodKey);
}
private String paramSignature(Parameter[] params) {
return Arrays.stream(params).map(this::docType).collect(Collectors.joining(","));
}
private String paramType(VariableElement param) {
return task.getTypes().erasure(param.asType()).toString();
}
private String docType(Parameter doc) {
return doc.type().qualifiedTypeName() + doc.type().dimension();
}
Optional<ConstructorDoc> constructorDoc(String methodKey) {
String className = methodKey.substring(0, methodKey.indexOf('#'));
return classDoc(className).flatMap(classDoc -> doConstructorDoc(classDoc, methodKey));
}
private Optional<ConstructorDoc> doConstructorDoc(ClassDoc classDoc, String methodKey) {
for (ConstructorDoc each : classDoc.constructors(false)) {
if (constructorMatches(methodKey, each)) return Optional.of(each);
}
return Optional.empty();
}
private boolean constructorMatches(String methodKey, ConstructorDoc doc) {
String docKey =
String.format(
"%s#<init>(%s)",
doc.containingClass().qualifiedName(), paramSignature(doc.parameters()));
return docKey.equals(methodKey);
}
Optional<ClassDoc> classDoc(String className) {
RootDoc index = index(className);
return Optional.ofNullable(index.classNamed(className));
}
/** Get or compute the javadoc for `className` */
RootDoc index(String className) {
if (needsUpdate(className)) topLevelClasses.put(className, doIndex(className));
return topLevelClasses.get(className).doc;
}
private boolean needsUpdate(String className) {
if (!topLevelClasses.containsKey(className)) return true;
IndexedDoc indexed = topLevelClasses.get(className);
try {
JavaFileObject fromDisk =
actualFileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH, className, JavaFileObject.Kind.SOURCE);
if (fromDisk == null) return true;
Instant modified = Instant.ofEpochMilli(fromDisk.getLastModified());
return indexed.updated.isBefore(modified);
} catch (IOException e) {
throw new RuntimeException();
}
}
/** Read all the Javadoc for `className` */
private IndexedDoc doIndex(String className) {
try {
JavaFileObject fromDisk =
actualFileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH, className, JavaFileObject.Kind.SOURCE);
if (fromDisk == null) {
LOG.warning("No source file for " + className);
return new IndexedDoc(EmptyRootDoc.INSTANCE, Instant.EPOCH);
}
JavaFileObject source = activeFile(fromDisk);
LOG.info("Found " + source.toUri() + " for " + className);
DocumentationTool.DocumentationTask task =
new JavadocTool()
.getTask(
null,
emptyFileManager,
JavaLanguageServer::onDiagnostic,
Javadocs.class,
null,
ImmutableList.of(source));
task.call();
return new IndexedDoc(
getSneakyReturn().orElse(EmptyRootDoc.INSTANCE),
Instant.ofEpochMilli(fromDisk.getLastModified()));
} catch (IOException e) {
throw new RuntimeException();
}
}
private JavaFileObject activeFile(JavaFileObject file) {
return activeContent
.apply(file.toUri())
.map(content -> (JavaFileObject) new StringFileObject(content, file.toUri()))
.orElse(file);
}
private Optional<RootDoc> getSneakyReturn() {
RootDoc result = sneakyReturn.get();
sneakyReturn.remove();
if (result == null) {
LOG.warning("index did not return a RootDoc");
return Optional.empty();
} else return Optional.of(result);
}
/** start(RootDoc) uses this to return its result to doIndex(...) */
private static ThreadLocal<RootDoc> sneakyReturn = new ThreadLocal<>();
/**
* Called by the javadoc tool
*
* <p>{@link Doclet}
*/
public static boolean start(RootDoc root) {
sneakyReturn.set(root);
return true;
}
/** Find the copy of src.zip that comes with the system-installed JDK */
static Optional<File> findSrcZip() {
Path path = Paths.get(System.getProperty("java.home"));
if (path.endsWith("jre")) path = path.getParent();
path = path.resolve("src.zip");
while (Files.isSymbolicLink(path)) {
try {
path = path.getParent().resolve(Files.readSymbolicLink(path));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (Files.exists(path)) return Optional.of(path.toFile());
else {
LOG.severe(String.format("Could not find %s", path));
return Optional.empty();
}
}
public void resolveCompletionItem(CompletionItem unresolved) {
if (unresolved.getData() == null || unresolved.getDocumentation() != null) return;
JsonPrimitive keyJson = (JsonPrimitive) unresolved.getData();
String key = keyJson.getAsString();
LOG.info("Resolve javadoc for " + key);
// my.package.MyClass#<init>()
if (key.contains("<init>")) {
constructorDoc(key)
.ifPresent(
doc ->
unresolved.setDocumentation(
Javadocs.htmlToMarkdown(doc.commentText())));
}
// my.package.MyClass#myMethod()
else if (key.contains("#")) {
methodDoc(key)
.ifPresent(
doc ->
unresolved.setDocumentation(
Javadocs.htmlToMarkdown(doc.commentText())));
}
// my.package.MyClass
else {
classDoc(key)
.ifPresent(
doc ->
unresolved.setDocumentation(
Javadocs.htmlToMarkdown(doc.commentText())));
}
}
/**
* Get the first sentence of a doc-comment.
*
* <p>In general, VS Code does a good job of only displaying the beginning of a doc-comment
* where appropriate. But if VS Code is displaying too much and you want to only show the first
* sentence, use this.
*/
public static String firstSentence(String doc) {
BreakIterator breaks = BreakIterator.getSentenceInstance();
breaks.setText(doc.replace('\n', ' '));
int start = breaks.first(), end = breaks.next();
if (start == -1 || end == -1) return doc;
return doc.substring(start, end).trim();
}
private static final Logger LOG = Logger.getLogger("main");
}