-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
pureComments.ts
56 lines (51 loc) · 1.61 KB
/
pureComments.ts
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
import * as acorn from 'acorn';
// @ts-ignore
import { base as basicWalker } from 'acorn-walk';
import { CommentDescription } from '../Module';
// patch up acorn-walk until class-fields are officially supported
basicWalker.FieldDefinition = function (node: any, st: any, c: any) {
if (node.computed) {
c(node.key, st, 'Expression');
}
if (node.value) {
c(node.value, st, 'Expression');
}
};
function handlePureAnnotationsOfNode(
node: acorn.Node,
state: { commentIndex: number; commentNodes: CommentDescription[] },
type: string = node.type
) {
let commentNode = state.commentNodes[state.commentIndex];
while (commentNode && node.start >= commentNode.end) {
markPureNode(node, commentNode);
commentNode = state.commentNodes[++state.commentIndex];
}
if (commentNode && commentNode.end <= node.end) {
basicWalker[type](node, state, handlePureAnnotationsOfNode);
}
}
function markPureNode(
node: acorn.Node & { annotations?: CommentDescription[] },
comment: CommentDescription
) {
if (node.annotations) {
node.annotations.push(comment);
} else {
node.annotations = [comment];
}
if (node.type === 'ExpressionStatement') {
node = (node as any).expression;
}
if (node.type === 'CallExpression' || node.type === 'NewExpression') {
(node as any).annotatedPure = true;
}
}
const pureCommentRegex = /[@#]__PURE__/;
const isPureComment = (comment: CommentDescription) => pureCommentRegex.test(comment.text);
export function markPureCallExpressions(comments: CommentDescription[], esTreeAst: acorn.Node) {
handlePureAnnotationsOfNode(esTreeAst, {
commentIndex: 0,
commentNodes: comments.filter(isPureComment)
});
}