-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
astUtils.ts
91 lines (83 loc) · 2.19 KB
/
astUtils.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
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
import {
AST_NODE_TYPES,
AST_TOKEN_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
const LINEBREAK_MATCHER = /\r\n|[\r\n\u2028\u2029]/;
function isOptionalChainPunctuator(
token: TSESTree.Token | TSESTree.Comment,
): boolean {
return token.type === AST_TOKEN_TYPES.Punctuator && token.value === '?.';
}
function isNotOptionalChainPunctuator(
token: TSESTree.Token | TSESTree.Comment,
): boolean {
return !isOptionalChainPunctuator(token);
}
function isNonNullAssertionPunctuator(
token: TSESTree.Token | TSESTree.Comment,
): boolean {
return token.type === AST_TOKEN_TYPES.Punctuator && token.value === '!';
}
function isNotNonNullAssertionPunctuator(
token: TSESTree.Token | TSESTree.Comment,
): boolean {
return !isNonNullAssertionPunctuator(token);
}
/**
* Returns true if and only if the node represents: foo?.() or foo.bar?.()
*/
function isOptionalOptionalChain(
node: TSESTree.Node,
): node is TSESTree.OptionalCallExpression {
return (
node.type === AST_NODE_TYPES.OptionalCallExpression &&
// this flag means the call expression itself is option
// i.e. it is foo.bar?.() and not foo?.bar()
node.optional
);
}
/**
* Returns true if and only if the node represents logical OR
*/
function isLogicalOrOperator(node: TSESTree.Node): boolean {
return (
node.type === AST_NODE_TYPES.LogicalExpression && node.operator === '||'
);
}
/**
* Determines whether two adjacent tokens are on the same line
*/
function isTokenOnSameLine(
left: TSESTree.Token,
right: TSESTree.Token,
): boolean {
return left.loc.end.line === right.loc.start.line;
}
/**
* Checks if a node is a type assertion:
* - x as foo
* - <foo>x
*/
function isTypeAssertion(
node: TSESTree.Node | undefined | null,
): node is TSESTree.TSAsExpression | TSESTree.TSTypeAssertion {
if (!node) {
return false;
}
return (
node.type === AST_NODE_TYPES.TSAsExpression ||
node.type === AST_NODE_TYPES.TSTypeAssertion
);
}
export {
isTypeAssertion,
isNonNullAssertionPunctuator,
isNotNonNullAssertionPunctuator,
isNotOptionalChainPunctuator,
isOptionalChainPunctuator,
isOptionalOptionalChain,
isTokenOnSameLine,
isLogicalOrOperator,
LINEBREAK_MATCHER,
};