-
-
Notifications
You must be signed in to change notification settings - Fork 153
/
jsdocUtils.js
580 lines (501 loc) · 13.7 KB
/
jsdocUtils.js
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import _ from 'lodash';
import tagNames from './tagNames';
const getFunctionParameterNames = (functionNode : Object) : Array<string> => {
const getParamName = (param) => {
if (_.has(param, 'name')) {
return param.name;
}
if (_.has(param, 'left.name')) {
return param.left.name;
}
if (param.type === 'ObjectPattern' || _.get(param, 'left.type') === 'ObjectPattern') {
return '<ObjectPattern>';
}
if (param.type === 'ArrayPattern' || _.get(param, 'left.type') === 'ArrayPattern') {
return '<ArrayPattern>';
}
if (param.type === 'RestElement') {
return param.argument.name;
}
if (param.type === 'TSParameterProperty') {
return getParamName(param.parameter);
}
throw new Error('Unsupported function signature format.');
};
return functionNode.params.map(getParamName);
};
/**
* Gets all parameter names, including those that refer to a path, e.g. "@param foo; @param foo.bar".
*/
const getJsdocParameterNamesDeep = (jsdoc : Object, targetTagName : string) : Array<string> => {
let jsdocParameterNames;
jsdocParameterNames = _.filter(jsdoc.tags, {
tag: targetTagName
});
jsdocParameterNames = _.map(jsdocParameterNames, 'name');
return jsdocParameterNames;
};
const getJsdocParameterNames = (jsdoc : Object, targetTagName : string) : Array<string> => {
let jsdocParameterNames;
jsdocParameterNames = getJsdocParameterNamesDeep(jsdoc, targetTagName);
jsdocParameterNames = jsdocParameterNames.filter((name) => {
return !name.includes('.');
});
return jsdocParameterNames;
};
const getPreferredTagName = (name : string, tagPreference : Object = {}) : string => {
if (_.values(tagPreference).includes(name)) {
return name;
}
if (_.has(tagPreference, name)) {
return tagPreference[name];
}
const preferredTagName = _.findKey(tagNames, (aliases) => {
return aliases.includes(name);
});
if (preferredTagName) {
return preferredTagName;
}
return name;
};
const isValidTag = (name : string, definedTags : Array) : boolean => {
const validTagNames = _.keys(tagNames).concat(_.flatten(_.values(tagNames)));
const additionalTags = definedTags;
const allTags = validTagNames.concat(additionalTags);
return allTags.includes(name);
};
const hasTag = (jsdoc : Object, targetTagName : string) : boolean => {
const targetTagLower = targetTagName.toLowerCase();
return _.some(jsdoc.tags, (doc : Object) => {
return doc.tag.toLowerCase() === targetTagLower;
});
};
const hasATag = (jsdoc : Object, targetTagNames : Array) : boolean => {
return targetTagNames.some((targetTagName) => {
return hasTag(jsdoc, targetTagName);
});
};
/**
* Checks if the JSDoc comment declares a return value.
*
* @param {JsDocTag} tag
* the tag which should be checked.
* @returns {boolean}
* true in case a return value is declared; otherwise false.
*/
const hasDefinedTypeReturnTag = (tag) => {
// The function should not continue in the event @returns is not defined...
if (typeof tag === 'undefined' || tag === null) {
return false;
}
// .. same applies if it declares `@returns {undefined}` or `@returns {void}`
const tagType = tag.type.trim();
if (tagType === 'undefined' || tagType === 'void') {
return false;
}
// In any other case, something must be returned, and
// a return statement is expected
return true;
};
const namepathDefiningTags = [
// NOT USEFUL WITHOUT NAMEPATH
'external', 'host',
'name',
'typedef',
// MAY BE USEFUL WITHOUT NAMEPATH
'event',
// MAY BE USEFUL WITHOUT NAMEPATH (OR
// BLOCK CAN USE NAMEPATH FROM ELSEWHERE)
'class', 'constructor',
'constant', 'const',
'callback',
'function', 'func', 'method',
'interface',
'member', 'var',
'mixin',
'namespace'
];
const namepathPointingTags = [
// NOT USEFUL WITHOUT NAMEPATH
'alias',
'augments', 'extends',
// `borrows` has a different format, however, so needs special parsing
'borrows',
'lends',
'memberof',
'memberof!',
'mixes',
'this',
// MAY BE USEFUL WITHOUT NAMEPATH
'emits',
'fires',
'listens'
];
const isNamepathDefiningTag = (tagName) => {
return namepathDefiningTags.includes(tagName);
};
const isNamepathPointingTag = (tagName, checkSeesForNamepaths) => {
return namepathPointingTags.includes(tagName) ||
tagName === 'see' && checkSeesForNamepaths;
};
const isNamepathTag = (tagName, checkSeesForNamepaths) => {
return isNamepathDefiningTag(tagName) ||
isNamepathPointingTag(tagName, checkSeesForNamepaths);
};
const potentiallyEmptyNamepathTags = [
// These may serve some minor purpose when empty or
// their namepath can be expressed elsewhere on the block
'event',
'callback',
'class', 'constructor',
'constant', 'const',
'function', 'func', 'method',
'interface',
'member', 'var',
'mixin',
'namespace',
'listens', 'fires', 'emits'
];
const isPotentiallyEmptyNamepathTag = (tag) => {
return potentiallyEmptyNamepathTags.includes(tag);
};
let tagsWithTypes = [
'class',
'constant',
'enum',
'implements',
'member',
'module',
'namespace',
'param',
'property',
'returns',
'throws',
'type',
'typedef',
'yields'
];
const closureTagsWithTypes = [
'package', 'private', 'protected', 'public', 'static'
];
const tagsWithTypesAliases = [
'constructor',
'const',
'var',
'arg',
'argument',
'prop',
'return',
'exception',
'yield'
];
tagsWithTypes = tagsWithTypes.concat(tagsWithTypesAliases, closureTagsWithTypes);
const isTagWithType = (tagName) => {
return tagsWithTypes.includes(tagName);
};
const LOOP_STATEMENTS = ['WhileStatement', 'DoWhileStatement', 'ForStatement', 'ForInStatement', 'ForOfStatement'];
const STATEMENTS_WITH_CHILDREN = [
'@loop',
'SwitchStatement',
'IfStatement',
'BlockStatement',
'TryStatement'
];
const RETURNFREE_STATEMENTS = [
'VariableDeclaration',
'ThrowStatement',
'FunctionDeclaration',
'BreakStatement',
'ContinueStatement',
'LabeledStatement',
'DebuggerStatement',
'EmptyStatement',
'WithStatement',
'ThrowStatement',
'ExpressionStatement'
];
const ENTRY_POINTS = ['FunctionDeclaration', 'ArrowFunctionExpression', 'FunctionExpression'];
/* eslint-disable sort-keys */
const lookupTable = {
ReturnStatement: {
is (node) {
return node.type === 'ReturnStatement';
},
check (node) {
/* istanbul ignore next */
if (!lookupTable.ReturnStatement.is(node)) {
return false;
}
// A return without any arguments just exits the function
// and is typically not documented at all in jsdoc.
if (node.argument === null) {
return false;
}
return true;
}
},
IfStatement: {
is (node) {
return node.type === 'IfStatement';
},
check (node) {
/* istanbul ignore next */
if (!lookupTable.IfStatement.is(node)) {
return false;
}
if (lookupTable['@default'].check(node.consequent)) {
return true;
}
if (node.alternate && lookupTable['@default'].check(node.alternate)) {
return true;
}
return false;
}
},
'@loop': {
is (node) {
return LOOP_STATEMENTS.includes(node.type);
},
check (node) {
return lookupTable['@default'].check(node.body);
}
},
SwitchStatement: {
is (node) {
return node.type === 'SwitchStatement';
},
check (node) {
for (const item of node.cases) {
for (const statement of item.consequent) {
if (lookupTable['@default'].check(statement)) {
return true;
}
}
}
return false;
}
},
TryStatement: {
is (node) {
return node.type === 'TryStatement';
},
check (node) {
/* istanbul ignore next */
if (!lookupTable.TryStatement.is(node)) {
return false;
}
if (lookupTable.BlockStatement.check(node.block)) {
return true;
}
if (node.handler && node.handler.body) {
if (lookupTable['@default'].check(node.handler.body)) {
return true;
}
}
if (lookupTable.BlockStatement.check(node.finalizer)) {
return true;
}
return false;
}
},
BlockStatement: {
is (node) {
return node.type === 'BlockStatement';
},
check (node, context) {
// E.g. the catch block statement is optional.
/* istanbul ignore next */
if (typeof node === 'undefined' || node === null) {
return false;
}
/* istanbul ignore next */
if (!lookupTable.BlockStatement.is(node)) {
return false;
}
for (const item of node.body) {
if (lookupTable['@default'].check(item, context)) {
return true;
}
}
return false;
}
},
FunctionExpression: {
is (node) {
return node.type === 'FunctionExpression';
},
check (node, context, ignoreAsync) {
return !ignoreAsync && node.async || lookupTable.BlockStatement.check(node.body, context);
}
},
ArrowFunctionExpression: {
is (node) {
return node.type === 'ArrowFunctionExpression';
},
check (node, context, ignoreAsync) {
// An expression always has a return value.
return node.expression ||
!ignoreAsync && node.async ||
lookupTable.BlockStatement.check(node.body, context);
}
},
FunctionDeclaration: {
is (node) {
return node.type === 'FunctionDeclaration';
},
check (node, context, ignoreAsync) {
return !ignoreAsync && node.async || lookupTable.BlockStatement.check(node.body, context);
}
},
'@default': {
check (node, context) {
// In case it is a `ReturnStatement`, we found what we were looking for
if (lookupTable.ReturnStatement.is(node)) {
return lookupTable.ReturnStatement.check(node, context);
}
// In case the element has children, we need to traverse them.
// Examples are BlockStatement, Choices, TryStatement, Loops, ...
for (const item of STATEMENTS_WITH_CHILDREN) {
if (lookupTable[item].is(node)) {
return lookupTable[item].check(node, context);
}
}
// Everything else cannot return anything.
/* istanbul ignore next */
if (RETURNFREE_STATEMENTS.includes(node.type)) {
return false;
}
/* istanbul ignore next */
// If we end up here, we stumbled upon an unknown element.
// Most likely it is enough to add it to the blacklist.
//
// throw new Error('Unknown node type: ' + node.type);
return false;
}
}
};
/**
* Checks if the source code returns a return value.
* It traverses the parsed source code and returns as
* soon as it stumbles upon the first return statement.
*
* @param {object} node
* the node which should be checked.
* @param {object} context
* @param {boolean} ignoreAsync
* ignore implicit async return.
* @returns {boolean}
* true in case the code returns a return value
*/
const hasReturnValue = (node, context, ignoreAsync) => {
// Loop through all of our entry points
for (const item of ENTRY_POINTS) {
if (lookupTable[item].is(node)) {
return lookupTable[item].check(node, context, ignoreAsync);
}
}
/* istanbul ignore next */
throw new Error(`Unknown element ${node.type}`);
};
/** @param {string} tag */
/*
const isInlineTag = (tag) => {
return /^(@link|@linkcode|@linkplain|@tutorial) /.test(tag);
};
*/
/**
* Parses GCC Generic/Template types
*
* @see {https://github.com/google/closure-compiler/wiki/Generic-Types}
* @param {JsDocTag} tag
* @returns {Array<string>}
*/
const parseClosureTemplateTag = (tag) => {
return tag.source
.split('@template')[1]
.split(',')
.map((type) => {
return type.trim();
});
};
/**
* Checks user option for `contexts` array, defaulting to
* contexts designated by the rule. Returns an array of
* ESTree AST types, indicating allowable contexts.
*
* @param {*} context
* @param {true|string[]} defaultContexts
* @returns {string[]}
*/
const enforcedContexts = (context, defaultContexts) => {
const {
/* istanbul ignore next */
contexts = defaultContexts === true ? [
'ArrowFunctionExpression',
'FunctionDeclaration',
'FunctionExpression'
] : defaultContexts
} = context.options[0] || {};
return contexts;
};
/**
* @param {string[]} contexts
* @param {Function} checkJsdoc
*/
const getContextObject = (contexts, checkJsdoc) => {
return contexts.reduce((obj, prop) => {
obj[prop] = checkJsdoc;
return obj;
}, {});
};
const filterTags = (tags = [], filter) => {
return tags.filter(filter);
};
const tagsWithNamesAndDescriptions = ['param', 'arg', 'argument', 'returns', 'return'];
const getTagsByType = (tags, tagPreference) => {
const descName = getPreferredTagName('description', tagPreference);
const tagsWithoutNames = [];
const tagsWithNames = filterTags(tags, (tag) => {
const {tag: tagName} = tag;
const tagWithName = tagsWithNamesAndDescriptions.includes(tagName);
if (!tagWithName && tagName !== descName) {
tagsWithoutNames.push(tag);
}
return tagWithName;
});
return {
tagsWithoutNames,
tagsWithNames
};
};
const getAncestor = (sourceCode, nde, depth, idx = 0) => {
if (idx === depth) {
return nde;
}
const prevToken = sourceCode.getTokenBefore(nde);
if (prevToken) {
return getAncestor(sourceCode, prevToken, depth, idx + 1);
}
return null;
};
export default {
enforcedContexts,
filterTags,
getAncestor,
getContextObject,
getFunctionParameterNames,
getJsdocParameterNames,
getJsdocParameterNamesDeep,
getPreferredTagName,
getTagsByType,
hasATag,
hasDefinedTypeReturnTag,
hasReturnValue,
hasTag,
isNamepathDefiningTag,
isNamepathTag,
isPotentiallyEmptyNamepathTag,
isTagWithType,
isValidTag,
parseClosureTemplateTag
};