forked from gajus/eslint-plugin-jsdoc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgetJSDocComment.js
92 lines (80 loc) · 2.6 KB
/
getJSDocComment.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
/**
* Obtained from {@link https://github.com/eslint/eslint/blob/master/lib/util/source-code.js#L313}
* @license MIT
*/
import astUtils from 'eslint/lib/util/ast-utils';
/**
* Check to see if its a ES6 export declaration.
*
* @param {ASTNode} astNode An AST node.
* @returns {boolean} whether the given node represents an export declaration.
* @private
*/
const looksLikeExport = function (astNode) {
return astNode.type === 'ExportDefaultDeclaration' || astNode.type === 'ExportNamedDeclaration' ||
astNode.type === 'ExportAllDeclaration' || astNode.type === 'ExportSpecifier';
};
/**
* Retrieves the JSDoc comment for a given node.
*
* @param {SourceCode} sourceCode The ESLint SourceCode
* @param {ASTNode} node The AST node to get the comment for.
* @returns {Token|null} The Block comment token containing the JSDoc comment
* for the given node or null if not found.
* @public
* @deprecated
*/
const getJSDocComment = function (sourceCode, node) {
/**
* Checks for the presence of a JSDoc comment for the given node and returns it.
*
* @param {ASTNode} astNode The AST node to get the comment for.
* @returns {Token|null} The Block comment token containing the JSDoc comment
* for the given node or null if not found.
* @private
*/
const findJSDocComment = (astNode) => {
const tokenBefore = sourceCode.getTokenBefore(astNode, {includeComments: true});
if (
tokenBefore &&
astUtils.isCommentToken(tokenBefore) &&
tokenBefore.type === 'Block' &&
tokenBefore.value.charAt(0) === '*' &&
astNode.loc.start.line - tokenBefore.loc.end.line <= 1
) {
return tokenBefore;
}
return null;
};
let parent = node.parent;
switch (node.type) {
case 'ClassDeclaration':
case 'FunctionDeclaration':
return findJSDocComment(looksLikeExport(parent) ? parent : node);
case 'ClassExpression':
return findJSDocComment(parent.parent);
case 'ArrowFunctionExpression':
case 'FunctionExpression':
if (parent.type !== 'CallExpression' && parent.type !== 'NewExpression') {
while (
!sourceCode.getCommentsBefore(parent).length &&
!/Function/u.test(parent.type) &&
parent.type !== 'MethodDefinition' &&
parent.type !== 'Property'
) {
parent = parent.parent;
if (!parent) {
break;
}
}
if (parent && parent.type !== 'FunctionDeclaration' && parent.type !== 'Program') {
return findJSDocComment(parent);
}
}
return findJSDocComment(node);
// falls through
default:
return null;
}
};
export default getJSDocComment;