forked from gajus/eslint-plugin-jsdoc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
iterateJsdoc.js
485 lines (403 loc) · 12.4 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
import _ from 'lodash';
import commentParser from 'comment-parser';
import jsdocUtils from './jsdocUtils';
import getJSDocComment from './eslint/getJSDocComment';
/**
*
* @param {object} commentNode
* @param {string} indent Whitespace
* @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,
commentParser.PARSERS.parse_type,
(str, data) => {
if (['example', 'return', 'returns', 'throws', 'exception'].includes(data.tag)) {
return null;
}
return commentParser.PARSERS.parse_name(str, data);
},
trim ?
commentParser.PARSERS.parse_description :
// 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?((.|\s)+)?/);
// 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 getUtils = (
node,
jsdoc,
jsdocNode,
{
tagNamePreference,
overrideReplacesDocs,
implementsReplacesDocs,
augmentsExtendsReplacesDocs
},
report,
context
) => {
const ancestors = context.getAncestors();
const sourceCode = context.getSourceCode();
const utils = {};
utils.getFunctionParameterNames = () => {
return jsdocUtils.getFunctionParameterNames(node);
};
utils.isConstructor = () => {
return node.parent && node.parent.kind === 'constructor';
};
utils.isSetter = () => {
return node.parent.kind === 'set';
};
utils.getJsdocParameterNamesDeep = () => {
const param = utils.getPreferredTagName('param');
if (!param) {
return false;
}
return jsdocUtils.getJsdocParameterNamesDeep(jsdoc, param);
};
utils.getJsdocParameterNames = () => {
const param = utils.getPreferredTagName('param');
if (!param) {
return false;
}
return jsdocUtils.getJsdocParameterNames(jsdoc, param);
};
utils.getPreferredTagName = (name, allowObjectReturn = false, defaultMessage = `Unexpected tag \`@${name}\``) => {
const ret = jsdocUtils.getPreferredTagName(name, tagNamePreference);
const isObject = ret && typeof ret === 'object';
if (ret === false || isObject && !ret.replacement) {
const message = isObject && ret.message || defaultMessage;
report(message, null, utils.getTags(name)[0]);
return false;
}
return isObject && !allowObjectReturn ? ret.replacement : ret;
};
utils.isValidTag = (name, definedTags) => {
return jsdocUtils.isValidTag(name, definedTags);
};
utils.hasATag = (name) => {
return jsdocUtils.hasATag(jsdoc, name);
};
utils.hasTag = (name) => {
return jsdocUtils.hasTag(jsdoc, name);
};
utils.avoidDocs = () => {
if (
overrideReplacesDocs !== false &&
(utils.hasTag('override') || utils.classHasTag('override')) ||
implementsReplacesDocs !== false &&
(utils.hasTag('implements') || utils.classHasTag('implements')) ||
// inheritdoc implies that all documentation is inherited; see https://jsdoc.app/tags-inheritdoc.html
utils.hasTag('inheritdoc') ||
augmentsExtendsReplacesDocs &&
(utils.hasATag(['augments', 'extends']) ||
utils.classHasTag('augments') ||
utils.classHasTag('extends'))) {
return true;
}
const exemptedBy = _.get(context, 'options[0].exemptedBy');
if (exemptedBy && exemptedBy.length && utils.getPresentTags(exemptedBy).length) {
return true;
}
return false;
};
utils.isNamepathDefiningTag = (tagName) => {
return jsdocUtils.isNamepathDefiningTag(tagName);
};
utils.isNamepathTag = (tagName, checkSeesForNamepaths) => {
return jsdocUtils.isNamepathTag(tagName, checkSeesForNamepaths);
};
utils.isTagWithType = (tagName) => {
return jsdocUtils.isTagWithType(tagName);
};
utils.passesEmptyNamepathCheck = (tag, allowEmptyNamepaths) => {
return !tag.name && allowEmptyNamepaths &&
jsdocUtils.isPotentiallyEmptyNamepathTag(tag.tag);
};
utils.hasDefinedTypeReturnTag = (tag) => {
return jsdocUtils.hasDefinedTypeReturnTag(tag);
};
utils.hasReturnValue = (ignoreAsync = false) => {
return jsdocUtils.hasReturnValue(node, context, ignoreAsync);
};
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(tags, tagNamePreference);
};
utils.getClassNode = () => {
const greatGrandParent = ancestors.slice(-3)[0];
const greatGrandParentValue = greatGrandParent && sourceCode.getFirstToken(greatGrandParent).value;
if (greatGrandParentValue === 'class') {
return greatGrandParent;
}
return false;
};
utils.getClassJsdoc = () => {
const classNode = utils.getClassNode();
const classJsdocNode = getJSDocComment(sourceCode, classNode);
if (classJsdocNode) {
const indent = ' '.repeat(classJsdocNode.loc.start.column);
return parseComment(classJsdocNode, indent);
}
return null;
};
utils.classHasTag = (tagName) => {
const classJsdoc = utils.getClassJsdoc();
return classJsdoc && jsdocUtils.hasTag(classJsdoc, tagName);
};
utils.forEachPreferredTag = (tagName, arrayHandler) => {
const targetTagName = utils.getPreferredTagName(tagName);
if (!targetTagName) {
return;
}
const matchingJsdocTags = _.filter(jsdoc.tags || [], {
tag: targetTagName
});
matchingJsdocTags.forEach((matchingJsdocTag) => {
arrayHandler(matchingJsdocTag, targetTagName);
});
};
utils.reportSettings = (message) => {
context.report({
loc: {
start: {
column: 1,
line: 1
}
},
message
});
};
return utils;
};
const getSettings = (context) => {
const settings = {};
// All rules
settings.ignorePrivate = Boolean(_.get(context, 'settings.jsdoc.ignorePrivate'));
// `check-tag-names` and many returns/param rules
settings.tagNamePreference = _.get(context, 'settings.jsdoc.tagNamePreference') || {};
// `check-types` and `no-undefined-types`
settings.preferredTypes = _.get(context, 'settings.jsdoc.preferredTypes') || {};
// `require-param`, `require-description`, `require-example`, `require-returns`
settings.overrideReplacesDocs = _.get(context, 'settings.jsdoc.overrideReplacesDocs');
settings.implementsReplacesDocs = _.get(context, 'settings.jsdoc.implementsReplacesDocs');
settings.augmentsExtendsReplacesDocs = _.get(context, 'settings.jsdoc.augmentsExtendsReplacesDocs');
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
*/
/**
* 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) => {
return {
create (context) {
return {
'Program:exit' () {
const comments = context.getSourceCode().getAllComments();
comments.forEach((comment) => {
if (!context.getSourceCode().getText(comment).startsWith('/**')) {
return;
}
const indent = ' '.repeat(comment.loc.start.column);
const jsdoc = parseComment(comment, indent, !ruleConfig.noTrim);
const settings = getSettings(context);
const report = makeReport(context, comment);
const jsdocNode = comment;
iterator({
context,
indent,
jsdoc,
jsdocNode,
node: null,
report,
settings: getSettings(context),
sourceCode: context.getSourceCode(),
utils: getUtils(null, jsdoc, jsdocNode, settings, report, context)
});
});
}
};
},
meta: ruleConfig.meta
};
};
export {
parseComment
};
/**
* @param {JsdocVisitor} iterator
* @param {{
* meta: any,
* contextDefaults?: true | string[],
* iterateAllJsdocs?: true,
* }} ruleConfig
*/
export default function iterateJsdoc (iterator, ruleConfig) {
const metaType = _.get(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.iterateAllJsdocs) {
return iterateAllJsdocs(iterator, {
meta: ruleConfig.meta,
noTrim: ruleConfig.noTrim
});
}
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) {
const sourceCode = context.getSourceCode();
const settings = getSettings(context);
const checkJsdoc = (node) => {
const jsdocNode = getJSDocComment(sourceCode, node);
if (!jsdocNode) {
return;
}
const indent = ' '.repeat(jsdocNode.loc.start.column);
const jsdoc = parseComment(jsdocNode, indent);
const report = makeReport(context, jsdocNode);
const utils = getUtils(
node,
jsdoc,
jsdocNode,
settings,
report,
context
);
if (
settings.ignorePrivate &&
utils.hasTag('private')
) {
return;
}
iterator({
context,
indent,
jsdoc,
jsdocNode,
node,
report,
settings,
sourceCode,
utils
});
};
if (ruleConfig.contextDefaults) {
const contexts = jsdocUtils.enforcedContexts(context, ruleConfig.contextDefaults);
return jsdocUtils.getContextObject(contexts, checkJsdoc);
}
return {
ArrowFunctionExpression: checkJsdoc,
FunctionDeclaration: checkJsdoc,
FunctionExpression: checkJsdoc
};
},
meta: ruleConfig.meta
};
}