-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
CheckJSDocStyle.java
466 lines (407 loc) · 15.5 KB
/
CheckJSDocStyle.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
/*
* Copyright 2015 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp.lint;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.AbstractCompiler;
import com.google.javascript.jscomp.CompilerPass;
import com.google.javascript.jscomp.DiagnosticGroup;
import com.google.javascript.jscomp.DiagnosticType;
import com.google.javascript.jscomp.ExportTestFunctions;
import com.google.javascript.jscomp.NodeTraversal;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.AbstractPreOrderCallback;
import com.google.javascript.jscomp.NodeUtil;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import java.util.List;
import javax.annotation.Nullable;
/**
* Checks for various JSDoc-related style issues, such as function definitions without JsDoc, params
* with no corresponding {@code @param} annotation, coding conventions not being respected, etc.
*/
public final class CheckJSDocStyle extends AbstractPostOrderCallback implements CompilerPass {
public static final DiagnosticType CONSTRUCTOR_DISALLOWED_JSDOC =
DiagnosticType.disabled("JSC_CONSTRUCTOR_DISALLOWED_JSDOC",
"Setting visibility on constructors is not yet supported.\n"
+ "See https://github.com/google/closure-compiler/issues/2761\n");
public static final DiagnosticType CLASS_DISALLOWED_JSDOC =
DiagnosticType.disabled("JSC_CLASS_DISALLOWED_JSDOC",
"@constructor annotations are redundant on classes.");
public static final DiagnosticType MISSING_JSDOC =
DiagnosticType.disabled("JSC_MISSING_JSDOC", "Function must have JSDoc.");
public static final DiagnosticType MISSING_PARAMETER_JSDOC =
DiagnosticType.disabled("JSC_MISSING_PARAMETER_JSDOC", "Parameter must have JSDoc.");
public static final DiagnosticType MIXED_PARAM_JSDOC_STYLES =
DiagnosticType.disabled("JSC_MIXED_PARAM_JSDOC_STYLES",
"Functions may not use both @param annotations and inline JSDoc");
public static final DiagnosticType MISSING_RETURN_JSDOC =
DiagnosticType.disabled(
"JSC_MISSING_RETURN_JSDOC",
"Function with non-trivial return must have JSDoc indicating the return type.");
public static final DiagnosticType MUST_BE_PRIVATE =
DiagnosticType.disabled("JSC_MUST_BE_PRIVATE", "Property {0} must be marked @private");
public static final DiagnosticType MUST_HAVE_TRAILING_UNDERSCORE =
DiagnosticType.disabled(
"JSC_MUST_HAVE_TRAILING_UNDERSCORE", "Private property {0} should end with ''_''");
public static final DiagnosticType OPTIONAL_PARAM_NOT_MARKED_OPTIONAL =
DiagnosticType.disabled("JSC_OPTIONAL_PARAM_NOT_MARKED_OPTIONAL",
"Parameter {0} is optional so its type must end with =");
public static final DiagnosticType WRONG_NUMBER_OF_PARAMS =
DiagnosticType.disabled("JSC_WRONG_NUMBER_OF_PARAMS", "Wrong number of @param annotations");
public static final DiagnosticType INCORRECT_PARAM_NAME =
DiagnosticType.disabled("JSC_INCORRECT_PARAM_NAME",
"Incorrect param name. Are your @param annotations in the wrong order?");
public static final DiagnosticType EXTERNS_FILES_SHOULD_BE_ANNOTATED =
DiagnosticType.disabled("JSC_EXTERNS_FILES_SHOULD_BE_ANNOTATED",
"Externs files should be annotated with @externs in the @fileoverview block.");
public static final DiagnosticType PREFER_BACKTICKS_TO_AT_SIGN_CODE =
DiagnosticType.disabled(
"JSC_PREFER_BACKTICKS_TO_AT_SIGN_CODE",
"Use `some_code` instead of '{'@code some_code'}'.");
public static final DiagnosticGroup ALL_DIAGNOSTICS =
new DiagnosticGroup(
CLASS_DISALLOWED_JSDOC,
CONSTRUCTOR_DISALLOWED_JSDOC,
MISSING_JSDOC,
MISSING_PARAMETER_JSDOC,
MIXED_PARAM_JSDOC_STYLES,
MISSING_RETURN_JSDOC,
MUST_BE_PRIVATE,
MUST_HAVE_TRAILING_UNDERSCORE,
OPTIONAL_PARAM_NOT_MARKED_OPTIONAL,
WRONG_NUMBER_OF_PARAMS,
INCORRECT_PARAM_NAME,
EXTERNS_FILES_SHOULD_BE_ANNOTATED,
PREFER_BACKTICKS_TO_AT_SIGN_CODE);
private final AbstractCompiler compiler;
public CheckJSDocStyle(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
NodeTraversal.traverse(compiler, root, this);
NodeTraversal.traverse(compiler, externs, new ExternsCallback());
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case FUNCTION:
visitFunction(t, n, parent);
break;
case CLASS:
visitClass(t, n);
break;
case ASSIGN:
checkStyleForPrivateProperties(t, n);
break;
case VAR:
case LET:
case CONST:
case STRING_KEY:
case SCRIPT:
break;
case MEMBER_FUNCTION_DEF:
case GETTER_DEF:
case SETTER_DEF:
// Don't need to call visitFunction because this JSDoc will be visited when the function is
// visited.
if (NodeUtil.getEnclosingClass(n) != null) {
checkStyleForPrivateProperties(t, n);
}
break;
default:
visitNonFunction(t, n);
}
}
private void checkForAtSignCodePresence(NodeTraversal t, Node n, @Nullable JSDocInfo jsDoc) {
if (jsDoc == null) {
return;
}
if (jsDoc.isAtSignCodePresent()) {
t.report(n, PREFER_BACKTICKS_TO_AT_SIGN_CODE);
}
}
private void visitNonFunction(NodeTraversal t, Node n) {
JSDocInfo jsDoc = n.getJSDocInfo();
checkForAtSignCodePresence(t, n, jsDoc);
}
private void checkStyleForPrivateProperties(NodeTraversal t, Node n) {
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(n);
checkForAtSignCodePresence(t, n, jsDoc);
String name;
if (n.isMemberFunctionDef() || n.isGetterDef() || n.isSetterDef()) {
name = n.getString();
} else {
checkState(n.isAssign());
Node lhs = n.getFirstChild();
if (!lhs.isGetProp()) {
return;
}
name = lhs.getLastChild().getString();
}
if (name.equals("constructor")) {
return;
}
if (jsDoc != null && name != null) {
if (compiler.getCodingConvention().isPrivate(name)
&& !jsDoc.getVisibility().equals(Visibility.PRIVATE)) {
t.report(n, MUST_BE_PRIVATE, name);
} else if (compiler.getCodingConvention().hasPrivacyConvention()
&& !compiler.getCodingConvention().isPrivate(name)
&& jsDoc.getVisibility().equals(Visibility.PRIVATE)) {
t.report(n, MUST_HAVE_TRAILING_UNDERSCORE, name);
}
}
}
private void visitFunction(NodeTraversal t, Node function, Node parent) {
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(function);
checkForAtSignCodePresence(t, function, jsDoc);
if (jsDoc == null && !hasAnyInlineJsDoc(function)) {
checkMissingJsDoc(t, function);
} else {
if (t.inGlobalScope()
|| hasAnyInlineJsDoc(function)
|| !jsDoc.getParameterNames().isEmpty()
|| jsDoc.hasReturnType()) {
checkParams(t, function, jsDoc);
}
checkReturn(t, function, jsDoc);
}
if (parent.isMemberFunctionDef()
&& "constructor".equals(parent.getString())
&& jsDoc != null
&& !jsDoc.getVisibility().equals(Visibility.INHERITED)) {
t.report(function, CONSTRUCTOR_DISALLOWED_JSDOC);
}
}
private void visitClass(NodeTraversal t, Node cls) {
JSDocInfo jsDoc = NodeUtil.getBestJSDocInfo(cls);
checkForAtSignCodePresence(t, cls, jsDoc);
if (jsDoc == null) {
return;
}
if (jsDoc.isConstructor()) {
t.report(cls, CLASS_DISALLOWED_JSDOC);
}
}
private void checkMissingJsDoc(NodeTraversal t, Node function) {
if (isFunctionThatShouldHaveJsDoc(t, function)) {
String name = NodeUtil.getName(function);
// Don't warn for test functions, setUp, tearDown, etc.
if (name == null || !ExportTestFunctions.isTestFunction(name)) {
t.report(function, MISSING_JSDOC);
}
}
}
/**
* Whether the given function should have JSDoc. True if it's a function declared
* in the global scope, or a method on a class which is declared in the global scope.
*/
private boolean isFunctionThatShouldHaveJsDoc(NodeTraversal t, Node function) {
if (!(t.inGlobalHoistScope() || t.inModuleScope())) {
return false;
}
if (NodeUtil.isFunctionDeclaration(function)) {
return true;
}
if (NodeUtil.isNameDeclaration(function.getGrandparent()) || function.getParent().isAssign()) {
return true;
}
if (function.getParent().isExport()) {
return true;
}
if (function.getGrandparent().isClassMembers()) {
Node memberNode = function.getParent();
if (memberNode.isMemberFunctionDef()) {
// A constructor with no parameters doesn't need JSDoc,
// but all other member functions do.
return !isConstructorWithoutParameters(function);
} else if (memberNode.isGetterDef() || memberNode.isSetterDef()) {
return true;
}
}
if (function.getGrandparent().isObjectLit()
&& NodeUtil.isCallTo(function.getGrandparent().getParent(), "Polymer")) {
return true;
}
return false;
}
private boolean isConstructorWithoutParameters(Node function) {
return function.getParent().matchesQualifiedName("constructor")
&& !NodeUtil.getFunctionParameters(function).hasChildren();
}
private void checkParams(NodeTraversal t, Node function, JSDocInfo jsDoc) {
if (jsDoc != null && jsDoc.isOverride()) {
return;
}
if (jsDoc != null && jsDoc.getType() != null) {
// Sometimes functions are declared with @type {function(Foo, Bar)} instead of
// @param {Foo} foo
// @param {Bar} bar
// which is fine.
return;
}
List<String> paramsFromJsDoc =
jsDoc == null
? ImmutableList.of()
: ImmutableList.copyOf(jsDoc.getParameterNames());
if (paramsFromJsDoc.isEmpty()) {
checkInlineParams(t, function);
} else {
Node paramList = NodeUtil.getFunctionParameters(function);
if (paramsFromJsDoc.size() != paramList.getChildCount()) {
t.report(paramList, WRONG_NUMBER_OF_PARAMS);
return;
}
Node param = paramList.getFirstChild();
for (int i = 0; i < paramsFromJsDoc.size(); i++) {
if (param.getJSDocInfo() != null) {
t.report(param, MIXED_PARAM_JSDOC_STYLES);
}
String name = paramsFromJsDoc.get(i);
JSTypeExpression paramType = jsDoc.getParameterType(name);
if (checkParam(t, param, name, paramType)) {
return;
}
param = param.getNext();
}
}
}
/**
* Checks that the inline type annotations are correct.
*/
private void checkInlineParams(NodeTraversal t, Node function) {
Node paramList = NodeUtil.getFunctionParameters(function);
for (Node param : paramList.children()) {
JSDocInfo jsDoc = param.getJSDocInfo();
if (jsDoc == null) {
t.report(param, MISSING_PARAMETER_JSDOC);
return;
} else {
JSTypeExpression paramType = jsDoc.getType();
checkNotNull(paramType, "Inline JSDoc info should always have a type");
checkParam(t, param, null, paramType);
}
}
}
/**
* Checks that the given parameter node has the given name, and that the given type is
* compatible.
* @param param If this is a non-NAME node, such as a destructuring pattern, skip the name check.
* @param name If null, skip the name check
* @return Whether a warning was reported
*/
private boolean checkParam(
NodeTraversal t, Node param, @Nullable String name, JSTypeExpression paramType) {
boolean nameOptional;
Node nodeToCheck = param;
if (param.isDefaultValue()) {
nodeToCheck = param.getFirstChild();
nameOptional = true;
} else if (param.isName()) {
nameOptional = param.getString().startsWith("opt_");
} else {
checkState(param.isDestructuringPattern() || param.isRest(), param);
nameOptional = false;
}
if (name == null || !nodeToCheck.isName()) {
// Skip the name check, but use "<unknown name>" for other errors that might be reported.
name = "<unknown name>";
} else if (!nodeToCheck.matchesQualifiedName(name)) {
t.report(nodeToCheck, INCORRECT_PARAM_NAME);
return true;
}
boolean jsDocOptional = paramType != null && paramType.isOptionalArg();
if (nameOptional && !jsDocOptional) {
t.report(nodeToCheck, OPTIONAL_PARAM_NOT_MARKED_OPTIONAL, name);
return true;
}
return false;
}
private boolean hasAnyInlineJsDoc(Node function) {
if (function.getFirstChild().getJSDocInfo() != null) {
// Inline return annotation.
return true;
}
for (Node param : NodeUtil.getFunctionParameters(function).children()) {
if (param.getJSDocInfo() != null) {
return true;
}
}
return false;
}
private void checkReturn(NodeTraversal t, Node function, JSDocInfo jsDoc) {
if (jsDoc != null
&& (jsDoc.hasType()
|| jsDoc.isConstructor()
|| jsDoc.hasReturnType()
|| jsDoc.isOverride())) {
return;
}
Node parent = function.getParent();
if (parent.isMemberFunctionDef() && parent.getString().equals("constructor")) {
// ES6 class constructors should never have "@return".
return;
}
if (function.getFirstChild().getJSDocInfo() != null) {
return;
}
FindNonTrivialReturn finder = new FindNonTrivialReturn();
NodeTraversal.traverse(compiler, function.getLastChild(), finder);
if (finder.found) {
t.report(function, MISSING_RETURN_JSDOC);
}
}
private static class FindNonTrivialReturn extends AbstractPreOrderCallback {
private boolean found;
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (found) {
return false;
}
// Shallow traversal, since we don't need to inspect within functions or expressions.
if (parent == null
|| NodeUtil.isControlStructure(parent)
|| NodeUtil.isStatementBlock(parent)) {
if (n.isReturn() && n.hasChildren()) {
found = true;
return false;
}
return true;
}
return false;
}
}
private static class ExternsCallback implements NodeTraversal.Callback {
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
return parent == null || n.isScript();
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isScript()) {
JSDocInfo info = n.getJSDocInfo();
if (info == null || !info.isExterns()) {
t.report(n, EXTERNS_FILES_SHOULD_BE_ANNOTATED);
}
}
}
}
}