/
CommentParser.js
65 lines (61 loc) · 2.12 KB
/
CommentParser.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
/**
* Doc Comment Parser class.
*
* @example
* for (let comment of node.leadingComments) {
* let tags = CommentParser.parse(comment);
* console.log(tags);
* }
*/
export default class CommentParser {
/**
* parse comment to tags.
* @param {ASTNode} commentNode - comment node.
* @param {string} commentNode.value - comment body.
* @param {string} commentNode.type - Block or Line.
* @returns {Tag[]} parsed comment.
*/
static parse(commentNode) {
if (!this.isESDoc(commentNode)) return [];
let comment = commentNode.value;
// TODO: refactor
comment = comment.replace(/\r\n/gm, '\n'); // for windows
comment = comment.replace(/^\t*\s?/gm, ''); // remove line head space
comment = comment.replace(/^\*\s?/, ''); // remove first '*'
comment = comment.replace(/\s$/, ''); // remove last space
comment = comment.replace(/^\s*\*\s?/gm, ''); // remove line head '*'
if (comment.charAt(0) !== '@') comment = '@desc ' + comment; // auto insert @desc
comment = comment.replace(/\s*$/, ''); // remove tail space.
comment = comment.replace(/^(@\w+)$/gm, '$1 \\TRUE'); // auto insert tag text to non-text tag (e.g. @interface)
comment = comment.replace(/^(@\w+)\s(.*)/gm, '\\Z$1\\Z$2'); // insert separator (\\Z@tag\\Ztext)
let lines = comment.split('\\Z');
let tagName = '';
let tagValue = '';
let tags = [];
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
if (line.charAt(0) === '@') {
tagName = line;
let nextLine = lines[i + 1];
if (nextLine.charAt(0) === '@') {
tagValue = '';
} else {
tagValue = nextLine;
i++;
}
tagValue = tagValue.replace('\\TRUE', '').replace(/^\n/, '').replace(/\n*$/, '');
tags.push({tagName, tagValue});
}
}
return tags;
}
/**
* judge doc comment or not.
* @param {ASTNode} commentNode - comment node.
* @returns {boolean} if true, this comment node is doc comment.
*/
static isESDoc(commentNode) {
if (commentNode.type !== 'Block') return false;
return commentNode.value.charAt(0) === '*';
}
}