This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
/
DocCommentGenerator.java
490 lines (412 loc) · 17.8 KB
/
DocCommentGenerator.java
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
/*
* Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sampleapi.generator;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Set;
import javax.lang.model.element.Modifier;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.List;
import java.util.HashMap;
import java.util.Map;
class DocCommentGenerator {
public enum Text {
BROWNFOX(BROWNFOX_TEXT),
NOWISTHETIME(NOWISTHETIME_TEXT),
THISPANGRAM(THISPANGRAM_TEXT),
LOREMIPSUM(LOREMIPSUM_TEXT),
LIEUROPANLINGUES(LIEUROPANLINGUES_TEXT),
CODE(CODE_TEXT);
String commentText;
Text(String text) {
commentText = text;
}
@Override
public String toString() {
return commentText;
}
}
public enum Tag {
AUTHOR("@author", "Cody J. Writer"),
PARAM("@param", ""),
RETURN("@return", Text.NOWISTHETIME.toString()),
SINCE("@since", "1.0"),
THROWS("@throws", "If problem detected"),
EXCEPTION("@exception", "If problem detected"),
SERIAL("@serial", ""),
SERIALDATA("@serialData", "The types and order of data could be here."),
SERIALFIELD("@serialField", "\n Serial field in special array"),
FX_PROPDESC("@propertyDescription", ""),
FX_DEFVALUE("@defaultValue", ""),
FX_TREATASPRIVATE("@treatAsPrivate", "");
String tagName;
String tagValue;
Tag(String tagName, String tagValue) {
this.tagName = tagName;
this.tagValue = tagValue;
}
public String toString() {
return value("", "");
}
public String value(String value) {
return value(value, "");
}
public String value(String value, String extra) {
return tagName
+ ((value.length() != 0) ? " " + value : "")
+ ((tagValue.length() != 0) ? " " + tagValue : "")
+ ((extra.length() != 0) ? " " + extra : "");
}
}
public enum InlineTag {
LITERAL("@literal", "Use < and > brackets instead of < and > escapes."),
CODE("@code", "(i) -> new Abc<Object>((i > 0) ? (i << 1) : 0)"),
LINK("@link", ""),
VALUE("@value", ""),
INDEX("@index", "", true);
String tagName;
String tagValue;
boolean counted;
Map<String, Integer> counters;
InlineTag(String tagName, String tagValue) {
this(tagName, tagValue, false);
}
InlineTag(String tagName, String tagValue, boolean counted) {
this.tagName = tagName;
this.tagValue = tagValue;
this.counted = counted;
if (counted) {
counters = new HashMap<>();
}
}
public String toString() {
return value("");
}
public String value(String value) {
String name = ((tagValue.length() != 0) ? " " + tagValue : "")
+ ((value.length() != 0) ? " " + value : "");
if (counted && !counters.containsKey(name)) {
counters.put(name, 0);
}
return "{" + tagName
+ name
+ (counted ? "_" + counters.put(name, counters.get(name) + 1) : "")
+ "}";
}
}
public static class LinkTag {
static String[] links = new String[] {
"Boolean",
"Boolean#TRUE",
"Boolean#Boolean(boolean)",
"Boolean#Boolean(String s)",
"Boolean#compare(boolean, boolean)",
"Boolean#compareTo(Boolean b)",
"java.util.Vector",
"java.util.Vector#elementCount",
"java.util.Vector#Vector(int)",
"java.util.Vector#Vector(int initialCapacity, int capacityIncrement)",
"java.util.Vector#indexOf(Object)",
"java.util.Vector#indexOf(Object o, int index)",
"java.lang.annotation" };
static int index = 0;
public static String nextSee() {
String next = "@see " + links[index];
index = (index + 1) % links.length;
return next;
}
public static String nextLink() {
String next = "Also check "
+ (((index % 2) == 0) ? "{@link " : "{@linkplain ")
+ links[index]
+ "} for details.\n";
index = (index + 1) % links.length;
return next;
}
}
public static class VersionTag {
static String[] versions = new String[] {
"1.5, 09/01/04",
"1.6, 12/11/06",
"1.7, 07/28/11",
"1.8, 04/19/14",
"9, 06/03/16" };
static int index = 0;
public static String nextVersion() {
String next = "@version " + versions[index];
index = (index + 1) % versions.length;
return next;
}
}
//
// getters (build comments for entities)
//
public String getPackageComment() {
return InlineTag.INDEX.value("PackageCommentLabel") + " "
+ Text.LOREMIPSUM
+ "\n<p>" + Text.LIEUROPANLINGUES
+ "\n" + Text.CODE
+ "\n" + LinkTag.nextLink()
+ "\n" + LinkTag.nextSee()
+ "\n" + Tag.SINCE + "\n";
}
String[] serialVals = new String[] { "include", "exclude" };
// static index to roll over "include/exclude"
static int serialValIdx = 0;
public String getBaseComment(JCClassDecl baseDecl, boolean toplevel) {
String buildComment = InlineTag.INDEX.value("BaseCommentLabel") + " ";
buildComment += Text.LIEUROPANLINGUES + "\n";
buildComment += "<p>It is possible to see inlined code:\n"
+ InlineTag.CODE
+ " is the example.\n\n";
buildComment += "<p>Literal use example.\n"
+ InlineTag.LITERAL + "\n\n";
buildComment += "<p>" + Text.THISPANGRAM + "\n"; // make comment longer
buildComment += "<p>" + LinkTag.nextLink() + "\n";
if (toplevel)
buildComment += "\n" + VersionTag.nextVersion() + "\n";
// @param for type params
List<JCTypeParameter> params = baseDecl.getTypeParameters();
int paramIndex = 0;
for (JCTypeParameter paramDecl : params) {
buildComment += Tag.PARAM.value(
"<" + paramDecl.getName().toString() + ">",
"the type of value set #" + paramIndex++)
+ "\n";
}
buildComment += "\n" + LinkTag.nextSee();
buildComment += "\n";
if (toplevel)
buildComment += Tag.AUTHOR + "\n";
buildComment += Tag.SINCE + "\n";
// for serial; currently no need to dig too deep
if (isSerializable(baseDecl) || isErrorOrException(baseDecl)) {
buildComment += "\n" + Tag.SERIAL.value(serialVals[serialValIdx]);
serialValIdx = (serialValIdx + 1) % 2;
}
return buildComment;
}
public String getConstComment() {
String buildComment = InlineTag.INDEX.value("ConstCommentLabel") + " ";
buildComment += Text.NOWISTHETIME + " " + Text.BROWNFOX + "\n";
buildComment += LinkTag.nextLink() + "\n";
buildComment += LinkTag.nextSee() + "\n";
buildComment += Tag.SINCE + "\n";
return buildComment;
}
public String getFieldComment(JCClassDecl baseDecl,
JCVariableDecl varDecl,
boolean isFxStyle) {
String buildComment = InlineTag.INDEX.value("FieldCommentLabel") + " ";
buildComment += Text.BROWNFOX + "<p>" + Text.NOWISTHETIME + "\n";
Set<Modifier> mods = varDecl.getModifiers().getFlags();
String varName = varDecl.getName().toString();
if (mods.contains(Modifier.STATIC) && mods.contains(Modifier.FINAL)) {
JCExpression init = varDecl.getInitializer();
if (init != null
&& !"null".equals(init.toString())
&& !"serialPersistentFields".equals(varName))
buildComment += "<p>The value of this constant is "
+ InlineTag.VALUE
+ ".\n";
}
buildComment += "<p>" + LinkTag.nextLink() + "\n";
if (isSerializable(baseDecl)) {
if (isErrorOrException(baseDecl)) {
buildComment += Tag.SERIAL + "\n";
} else if ("serialPersistentFields".equals(varName)) {
JCNewArray sfList = (JCNewArray)varDecl.getInitializer();
for (JCExpression sf : sfList.getInitializers()) {
List<JCExpression> args = ((JCNewClass)sf).getArguments();
String sfName = ((JCLiteral)args.get(0)).getValue().toString();
String sfClass = ((JCIdent)args.get(1)).getName().toString();
String sfType = sfClass.substring(0, sfClass.indexOf(".class"));
buildComment += Tag.SERIALFIELD.value(sfName + " " + sfType)
+ "\n";
}
} else {
buildComment += Tag.SERIAL.value("Very important value.") + "\n";
}
}
if (isFxStyle) {
// set default value
String varType = varDecl.getType().toString();
buildComment += Tag.FX_DEFVALUE.value(defValue(varType)) + "\n";
}
buildComment += LinkTag.nextSee() + "\n";
return buildComment;
}
public String getMethodComment(JCClassDecl baseDecl,
JCMethodDecl methodDecl,
boolean isFxStyle) {
String buildComment = InlineTag.INDEX.value("MethodCommentLabel") + " ";
buildComment += Text.BROWNFOX + "\n<p>" + Text.THISPANGRAM + "\n";
buildComment += "<p>" + LinkTag.nextLink() + "\n";
buildComment += "<p>Literal use example.\n"
+ InlineTag.LITERAL + "\n\n";
// @param for type params
List<JCTypeParameter> tparams = methodDecl.getTypeParameters();
int tparamIndex = 0;
for (JCTypeParameter paramDecl : tparams) {
String paramDeclString = paramDecl.getName().toString();
// simplify it (could contain 'extend'/'super' clauses
int spacePos = paramDeclString.indexOf(' ');
if (spacePos != -1)
paramDeclString = paramDeclString.substring(0, spacePos);
buildComment += Tag.PARAM.value(
"<" + paramDeclString + ">",
"the type of value set #" + tparamIndex++)
+ "\n";
}
// @param
List<JCVariableDecl> params = methodDecl.getParameters();
int paramIndex = 0;
for (JCVariableDecl paramDecl : params) {
buildComment += Tag.PARAM.value(
paramDecl.getName().toString(),
"an income parameter #" + paramIndex++)
+ "\n";
}
// @return
JCTree retType = methodDecl.getReturnType(); // null for constructors
if (retType != null && !"void".equals(retType.toString()))
buildComment += Tag.RETURN + "\n";
// @throws/@exception
Tag t = isDerived(baseDecl) ? Tag.EXCEPTION : Tag.THROWS;
List<JCExpression> throwTypes = methodDecl.getThrows();
for (JCExpression throwsExp : throwTypes) {
buildComment += t.value(throwsExp.toString()) + "\n";
}
if (isSerializable(baseDecl)) {
switch (methodDecl.getName().toString()) {
case "writeObject":
case "readObject":
case "writeExternal":
case "readExternal":
case "writeReplace":
case "readResolve":
buildComment += Tag.SERIALDATA + "\n";
break;
default:
}
}
if (isFxStyle) {
// @propertySetter/Getter + Description
if (!"void".equals(retType.toString())) {
buildComment += Tag.FX_DEFVALUE.value(defValue(retType.toString()))
+ "\n";
}
buildComment += Tag.FX_PROPDESC.value(Text.BROWNFOX.toString()) + "\n";
// @treatAsPrivate
if (methodDecl.getModifiers().getFlags().contains(Modifier.PUBLIC))
buildComment += Tag.FX_TREATASPRIVATE + "\n";
}
// @see
buildComment += LinkTag.nextSee() + "\n";
// @since
buildComment += Tag.SINCE + "\n";
return buildComment;
}
//
// util methods
//
private boolean isErrorOrException(JCClassDecl baseDecl) {
JCExpression ext = baseDecl.getExtendsClause();
if (ext != null) {
String extClassName = ext.toString();
if (extClassName.contains("Error") || extClassName.contains("Exception"))
return true;
}
return false;
}
private boolean isSerializable(JCClassDecl baseDecl) {
List<JCExpression> impls = baseDecl.getImplementsClause();
for (JCExpression impl : impls) {
if (impl.toString().contains("Serializable"))
return true;
}
return false;
}
private boolean isDerived(JCClassDecl baseDecl) {
return (baseDecl.getExtendsClause() == null) ? false : true;
}
private String defValue(String type) {
switch (type) {
case "boolean":
return "true";
case "byte": case "char": case "int": case "long":
case "Integer": case "Long":
return "1";
case "float": case "double": case "Float": case "Double":
return "1.0";
case "String":
return "string";
default:
return "null";
}
}
private static final String BROWNFOX_TEXT =
"The quick brown fox jumps over the lazy dog.\n";
private static final String NOWISTHETIME_TEXT =
"Now is the time for all good men to come to the aid of the party.\n";
private static final String THISPANGRAM_TEXT =
"This pangram contains four a's, one b, two c's, one d, thirty e's,\n" +
"six f's, five g's, seven h's, eleven i's, one j, one k, two l's,\n" +
"two m's, eighteen n's, fifteen o's, two p's, one q, five r's,\n" +
"twenty-seven s's, eighteen t's, two u's, seven v's, eight w's,\n" +
"two x's, three y's, & one z.";
private static final String LOREMIPSUM_TEXT =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\n" +
"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut\n" +
"enim ad minim veniam, quis nostrud exercitation ullamco laboris\n" +
"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n" +
"in reprehenderit in voluptate velit esse cillum dolore eu fugiat\n" +
"nulla pariatur. Excepteur sint occaecat cupidatat non proident,\n" +
"sunt in culpa qui officia deserunt mollit anim id est laborum.\n";
private static final String LIEUROPANLINGUES_TEXT =
"Li Europan lingues es membres del sam familie. Lor separat existentie\n" +
"es un myth. Por scientie, musica, sport etc, litot Europa usa li sam\n" +
"vocabular. Li lingues differe solmen in li grammatica, li pronunciation\n" +
"e li plu commun vocabules. Omnicos directe al desirabilite de un nov\n" +
"lingua franca: On refusa continuar payar custosi traductores.\n" +
"\n" +
"<p>At solmen va esser necessi far uniform grammatica, pronunciation\n" +
"e plu commun paroles. Ma quande lingues coalesce, li grammatica del\n" +
"resultant lingue es plu simplic e regulari quam ti del coalescent\n" +
"lingues. Li nov lingua franca va esser plu simplic e regulari quam\n" +
"li existent Europan lingues. It va esser tam simplic quam Occidental\n" +
"in fact, it va esser Occidental. A un Angleso it va semblar un simplificat\n" +
"Angles, quam un skeptic Cambridge amico dit me que Occidental es.\n";
private static final String CODE_TEXT =
"<pre>\n" +
"public void checkLanguage(Language lang) throws Exception {\n" +
" if (lang.getName().equals(\"Java\")) {\n" +
" System.out.println(\"Warning! Hot!\");\n" +
" else {\n" +
" throw new LooserException();\n" +
" }\n" +
"}\n" +
"</pre>\n";
}