-
-
Notifications
You must be signed in to change notification settings - Fork 153
/
iterateJsdoc.js
724 lines (612 loc) · 18.1 KB
/
iterateJsdoc.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
// eslint-disable-next-line import/no-named-default
import {default as commentParser, stringify as commentStringify} from 'comment-parser';
import _ from 'lodash';
import jsdocUtils from './jsdocUtils';
import {getJSDocComment, getReducedASTNode} from './eslint/getJSDocComment';
const globalState = new Map();
const skipSeeLink = (parser) => {
return (str, data) => {
if (data.tag === 'see' && (/\{@link.+?\}/u).test(str)) {
return null;
}
return parser(str, data);
};
};
/**
*
* @param {object} commentNode
* @param {string} indent Whitespace
* @param {boolean} [trim=true]
* @returns {object}
*/
const parseComment = (commentNode, indent, trim = true) => {
// Preserve JSDoc block start/end indentation.
return commentParser(`${indent}/*${commentNode.value}${indent}*/`, {
// @see https://github.com/yavorskiy/comment-parser/issues/21
parsers: [
commentParser.PARSERS.parse_tag,
skipSeeLink(
(str, data) => {
if (['default', 'defaultvalue'].includes(data.tag)) {
return null;
}
return commentParser.PARSERS.parse_type(str, data);
},
),
skipSeeLink(
(str, data) => {
if ([
'example', 'return', 'returns', 'throws', 'exception',
'access', 'version', 'since', 'license', 'author',
'default', 'defaultvalue',
].includes(data.tag)) {
return null;
}
return commentParser.PARSERS.parse_name(str, data);
},
),
// parse_description
(str, data) => {
// Only expected throw in previous step is if bad name (i.e.,
// missing end bracket on optional name), but `@example`
// skips name parsing
/* istanbul ignore next */
if (data.errors && data.errors.length) {
return null;
}
// Tweak original regex to capture only single optional space
const result = str.match(/^ ?((.|\s)+)?/u);
// Always has at least whitespace due to `indent` we've added
/* istanbul ignore next */
if (result) {
return {
data: {
description: result[1] === undefined ? '' : result[1],
},
source: result[0],
};
}
// Always has at least whitespace due to `indent` we've added
/* istanbul ignore next */
return null;
},
],
trim,
})[0] || {};
};
const getBasicUtils = (context, {tagNamePreference, mode}) => {
const utils = {};
utils.reportSettings = (message) => {
context.report({
loc: {
start: {
column: 1,
line: 1,
},
},
message,
});
};
utils.getPreferredTagNameObject = ({tagName}) => {
const ret = jsdocUtils.getPreferredTagName(context, mode, tagName, tagNamePreference);
const isObject = ret && typeof ret === 'object';
if (ret === false || isObject && !ret.replacement) {
return {
blocked: true,
tagName,
};
}
return ret;
};
return utils;
};
const getUtils = (
node,
jsdoc,
jsdocNode,
settings,
report,
context,
iteratingAll,
ruleConfig,
) => {
const ancestors = context.getAncestors();
const sourceCode = context.getSourceCode();
const utils = getBasicUtils(context, settings);
const {
tagNamePreference,
overrideReplacesDocs,
implementsReplacesDocs,
augmentsExtendsReplacesDocs,
maxLines,
minLines,
mode,
} = settings;
utils.isIteratingFunction = () => {
return !iteratingAll || [
'MethodDefinition',
'ArrowFunctionExpression',
'FunctionDeclaration',
'FunctionExpression',
].includes(node && node.type);
};
utils.isVirtualFunction = () => {
return iteratingAll && utils.hasATag(['callback', 'function', 'func', 'method']);
};
utils.stringify = (tagBlock, tag) => {
const indent = tag ?
jsdocUtils.getIndent({
text: sourceCode.getText(
tag,
tag.loc.start.column,
),
}) :
jsdocUtils.getIndent(sourceCode);
if (ruleConfig.noTrim) {
const lastTag = tagBlock.tags[tagBlock.tags.length - 1];
lastTag.description = lastTag.description.replace(/\n$/, '');
}
return commentStringify([tagBlock], {indent}).slice(indent.length - 1);
};
utils.reportJSDoc = (msg, tag, handler) => {
report(msg, handler ? (fixer) => {
handler();
const replacement = utils.stringify(jsdoc, node);
return fixer.replaceText(jsdocNode, replacement);
} : null, tag);
};
utils.flattenRoots = (params) => {
return jsdocUtils.flattenRoots(params);
};
utils.getFunctionParameterNames = () => {
return jsdocUtils.getFunctionParameterNames(node);
};
utils.isConstructor = () => {
return jsdocUtils.isConstructor(node);
};
utils.getJsdocTagsDeep = (tagName) => {
const name = utils.getPreferredTagName({tagName});
if (!name) {
return false;
}
return jsdocUtils.getJsdocTagsDeep(jsdoc, name);
};
utils.getPreferredTagName = ({tagName, skipReportingBlockedTag = false, allowObjectReturn = false, defaultMessage = `Unexpected tag \`@${tagName}\``}) => {
const ret = jsdocUtils.getPreferredTagName(context, mode, tagName, tagNamePreference);
const isObject = ret && typeof ret === 'object';
if (utils.hasTag(tagName) && (ret === false || isObject && !ret.replacement)) {
if (skipReportingBlockedTag) {
return {
blocked: true,
tagName,
};
}
const message = isObject && ret.message || defaultMessage;
report(message, null, utils.getTags(tagName)[0]);
return false;
}
return isObject && !allowObjectReturn ? ret.replacement : ret;
};
utils.isValidTag = (name, definedTags) => {
return jsdocUtils.isValidTag(context, mode, name, definedTags);
};
utils.hasATag = (name) => {
return jsdocUtils.hasATag(jsdoc, name);
};
utils.hasTag = (name) => {
return jsdocUtils.hasTag(jsdoc, name);
};
utils.comparePaths = (name) => {
return jsdocUtils.comparePaths(name);
};
utils.dropPathSegmentQuotes = (name) => {
return jsdocUtils.dropPathSegmentQuotes(name);
};
utils.avoidDocs = () => {
if (
overrideReplacesDocs !== false &&
(utils.hasTag('override') || utils.classHasTag('override')) ||
implementsReplacesDocs !== false &&
(utils.hasTag('implements') || utils.classHasTag('implements')) ||
augmentsExtendsReplacesDocs &&
(utils.hasATag(['augments', 'extends']) ||
utils.classHasTag('augments') ||
utils.classHasTag('extends'))) {
return true;
}
if (jsdocUtils.exemptSpeciaMethods(
jsdoc, node, context, ruleConfig.meta.schema,
)) {
return true;
}
const exemptedBy = context.options[0]?.exemptedBy ?? [
'inheritDoc',
...mode === 'closure' ? [] : ['inheritdoc'],
];
if (exemptedBy.length && utils.getPresentTags(exemptedBy).length) {
return true;
}
return false;
};
utils.tagMustHaveEitherTypeOrNamePosition = (tagName) => {
return jsdocUtils.tagMustHaveEitherTypeOrNamePosition(tagName);
};
utils.tagMightHaveEitherTypeOrNamePosition = (tagName) => {
return jsdocUtils.tagMightHaveEitherTypeOrNamePosition(mode, tagName);
};
utils.tagMustHaveNamePosition = (tagName) => {
return jsdocUtils.tagMustHaveNamePosition(tagName);
};
utils.tagMightHaveNamePosition = (tagName) => {
return jsdocUtils.tagMightHaveNamePosition(mode, tagName);
};
utils.tagMustHaveTypePosition = (tagName) => {
return jsdocUtils.tagMustHaveTypePosition(mode, tagName);
};
utils.tagMightHaveTypePosition = (tagName) => {
return jsdocUtils.tagMightHaveTypePosition(mode, tagName);
};
utils.isNamepathDefiningTag = (tagName) => {
return jsdocUtils.isNamepathDefiningTag(mode, tagName);
};
utils.hasDefinedTypeReturnTag = (tag) => {
return jsdocUtils.hasDefinedTypeReturnTag(tag);
};
utils.hasReturnValue = () => {
return jsdocUtils.hasReturnValue(node);
};
utils.hasThrowValue = () => {
return jsdocUtils.hasThrowValue(node);
};
utils.isAsync = () => {
return node.async;
};
utils.getTags = (tagName) => {
return utils.filterTags((item) => {
return item.tag === tagName;
});
};
utils.getPresentTags = (tagList) => {
return utils.filterTags((tag) => {
return tagList.includes(tag.tag);
});
};
utils.filterTags = (filter) => {
return jsdocUtils.filterTags(jsdoc.tags, filter);
};
utils.getTagsByType = (tags) => {
return jsdocUtils.getTagsByType(context, mode, tags, tagNamePreference);
};
utils.hasOptionTag = (tagName) => {
const {tags} = context.options[0] ?? {};
return Boolean(tags && tags.includes(tagName));
};
utils.getClassNode = () => {
return [...ancestors, node].reverse().find((parent) => {
return parent && ['ClassDeclaration', 'ClassExpression'].includes(parent.type);
}) || null;
};
utils.getClassJsdoc = () => {
const classNode = utils.getClassNode();
if (!classNode) {
return null;
}
const classJsdocNode = getJSDocComment(sourceCode, classNode, {
maxLines,
minLines,
});
if (classJsdocNode) {
const indent = ' '.repeat(classJsdocNode.loc.start.column);
return parseComment(classJsdocNode, indent);
}
return null;
};
utils.classHasTag = (tagName) => {
const classJsdoc = utils.getClassJsdoc();
return Boolean(classJsdoc) && jsdocUtils.hasTag(classJsdoc, tagName);
};
utils.forEachPreferredTag = (tagName, arrayHandler, skipReportingBlockedTag = false) => {
const targetTagName = utils.getPreferredTagName({
skipReportingBlockedTag,
tagName,
});
if (!targetTagName ||
skipReportingBlockedTag && targetTagName && typeof targetTagName === 'object'
) {
return;
}
const matchingJsdocTags = _.filter(jsdoc.tags || [], {
tag: targetTagName,
});
matchingJsdocTags.forEach((matchingJsdocTag) => {
arrayHandler(matchingJsdocTag, targetTagName);
});
};
return utils;
};
const getSettings = (context) => {
/* eslint-disable sort-keys-fix/sort-keys-fix */
const settings = {
// All rules
ignorePrivate: Boolean(context.settings.jsdoc?.ignorePrivate),
maxLines: Number(context.settings.jsdoc?.maxLines ?? 1),
minLines: Number(context.settings.jsdoc?.minLines ?? 0),
// `check-tag-names` and many returns/param rules
tagNamePreference: context.settings.jsdoc?.tagNamePreference ?? {},
// `check-types` and `no-undefined-types`
preferredTypes: context.settings.jsdoc?.preferredTypes ?? {},
// `require-param`, `require-description`, `require-example`, `require-returns`
overrideReplacesDocs: context.settings.jsdoc?.overrideReplacesDocs,
implementsReplacesDocs: context.settings.jsdoc?.implementsReplacesDocs,
augmentsExtendsReplacesDocs: context.settings.jsdoc?.augmentsExtendsReplacesDocs,
// Many rules, e.g., `check-tag-names`
mode: context.settings.jsdoc?.mode ??
(context.parserPath.includes('@typescript-eslint') ? 'typescript' : 'jsdoc'),
};
/* eslint-enable sort-keys-fix/sort-keys-fix */
return settings;
};
/**
* Create the report function
*
* @param {object} context
* @param {object} commentNode
*/
const makeReport = (context, commentNode) => {
const report = (message, fix = null, jsdocLoc = null, data = null) => {
let loc;
if (jsdocLoc) {
const lineNumber = commentNode.loc.start.line + jsdocLoc.line;
loc = {
end: {line: lineNumber},
start: {line: lineNumber},
};
if (jsdocLoc.column) {
const colNumber = commentNode.loc.start.column + jsdocLoc.column;
loc.end.column = colNumber;
loc.start.column = colNumber;
}
}
context.report({
data,
fix,
loc,
message,
node: commentNode,
});
};
return report;
};
/**
* @typedef {ReturnType<typeof getUtils>} Utils
* @typedef {ReturnType<typeof getSettings>} Settings
* @typedef {(
* arg: {
* context: object,
* sourceCode: object,
* indent: string,
* jsdoc: object,
* jsdocNode: object,
* node: object | null,
* report: ReturnType<typeof makeReport>,
* settings: Settings,
* utils: Utils,
* }
* ) => any } JsdocVisitor
*/
const iterate = (
ruleConfig, context, lines, jsdocNode, node, settings,
sourceCode, iterator, state, iteratingAll,
) => {
const sourceLine = lines[jsdocNode.loc.start.line - 1];
const indent = sourceLine.charAt(0).repeat(jsdocNode.loc.start.column);
const jsdoc = parseComment(jsdocNode, indent, !ruleConfig.noTrim);
const report = makeReport(context, jsdocNode);
const utils = getUtils(
node,
jsdoc,
jsdocNode,
settings,
report,
context,
iteratingAll,
ruleConfig,
);
if (
settings.ignorePrivate &&
!ruleConfig.checkPrivate &&
(utils.hasTag('private') || _.filter(jsdoc.tags, {
tag: 'access',
}).some(({description}) => {
return description === 'private';
}))
) {
return;
}
iterator({
context,
globalState,
indent,
iteratingAll,
jsdoc,
jsdocNode,
node,
report,
settings,
sourceCode,
state,
utils,
});
};
/**
* Create an eslint rule that iterates over all JSDocs, regardless of whether
* they are attached to a function-like node.
*
* @param {JsdocVisitor} iterator
* @param {{meta: any}} ruleConfig
*/
const iterateAllJsdocs = (iterator, ruleConfig) => {
const trackedJsdocs = [];
const callIterator = (context, node, jsdocNodes, state, lastCall) => {
const sourceCode = context.getSourceCode();
const settings = getSettings(context);
const {lines} = sourceCode;
const utils = getBasicUtils(context, settings);
jsdocNodes.forEach((jsdocNode) => {
if (!(/^\/\*\*\s/).test(sourceCode.getText(jsdocNode))) {
return;
}
iterate(
ruleConfig, context, lines, jsdocNode, node,
settings, sourceCode, iterator,
state, true,
);
});
if (lastCall && ruleConfig.exit) {
ruleConfig.exit({
context,
state,
utils,
});
}
};
return {
create (context) {
const sourceCode = context.getSourceCode();
const settings = getSettings(context);
const state = {};
return {
'*:not(Program)' (node) {
const reducedNode = getReducedASTNode(node, sourceCode);
if (node !== reducedNode) {
return;
}
const comment = getJSDocComment(sourceCode, node, settings);
if (trackedJsdocs.includes(comment)) {
return;
}
if (!comment) {
if (ruleConfig.nonComment) {
ruleConfig.nonComment({
node,
state,
});
}
return;
}
trackedJsdocs.push(comment);
callIterator(context, node, [comment], state);
},
'Program:exit' () {
const allComments = sourceCode.getAllComments();
const untrackedJSdoc = allComments.filter((node) => {
return !trackedJsdocs.includes(node);
});
callIterator(context, null, untrackedJSdoc, state, true);
},
};
},
meta: ruleConfig.meta,
};
};
/**
* Create an eslint rule that iterates over all JSDocs, regardless of whether
* they are attached to a function-like node.
*
* @param {JsdocVisitor} iterator
* @param {{meta: any}} ruleConfig
*/
const checkFile = (iterator, ruleConfig) => {
return {
create (context) {
const sourceCode = context.getSourceCode();
const settings = getSettings(context);
return {
'Program:exit' () {
const allComments = sourceCode.getAllComments();
const {lines} = sourceCode;
const utils = getBasicUtils(context, settings);
iterator({
allComments,
context,
lines,
makeReport,
settings,
sourceCode,
utils,
});
},
};
},
meta: ruleConfig.meta,
};
};
export {
getSettings,
parseComment,
};
/**
* @param {JsdocVisitor} iterator
* @param {{
* meta: any,
* contextDefaults?: true | string[],
* iterateAllJsdocs?: true,
* }} ruleConfig
*/
export default function iterateJsdoc (iterator, ruleConfig) {
const metaType = ruleConfig?.meta?.type;
if (!metaType || !['problem', 'suggestion', 'layout'].includes(metaType)) {
throw new TypeError('Rule must include `meta.type` option (with value "problem", "suggestion", or "layout")');
}
if (typeof iterator !== 'function') {
throw new TypeError('The iterator argument must be a function.');
}
if (ruleConfig.checkFile) {
return checkFile(iterator, ruleConfig);
}
if (ruleConfig.iterateAllJsdocs) {
return iterateAllJsdocs(iterator, ruleConfig);
}
return {
/**
* The entrypoint for the JSDoc rule.
*
* @param {*} context
* a reference to the context which hold all important information
* like settings and the sourcecode to check.
* @returns {object}
* a list with parser callback function.
*/
create (context) {
let contexts;
if (ruleConfig.contextDefaults) {
contexts = jsdocUtils.enforcedContexts(context, ruleConfig.contextDefaults);
if (contexts.includes('any')) {
return iterateAllJsdocs(iterator, ruleConfig).create(context);
}
}
const sourceCode = context.getSourceCode();
const settings = getSettings(context);
const {lines} = sourceCode;
const checkJsdoc = (node) => {
const jsdocNode = getJSDocComment(sourceCode, node, settings);
if (!jsdocNode) {
return;
}
iterate(
ruleConfig, context, lines, jsdocNode, node,
settings, sourceCode, iterator,
);
};
if (ruleConfig.contextDefaults) {
return jsdocUtils.getContextObject(contexts, checkJsdoc);
}
return {
ArrowFunctionExpression: checkJsdoc,
FunctionDeclaration: checkJsdoc,
FunctionExpression: checkJsdoc,
};
},
meta: ruleConfig.meta,
};
}