-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
prefer-optional-chain.ts
219 lines (206 loc) · 7 KB
/
prefer-optional-chain.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
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
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { RuleFix } from '@typescript-eslint/utils/ts-eslint';
import * as ts from 'typescript';
import {
createRule,
getOperatorPrecedence,
getParserServices,
OperatorPrecedence,
} from '../util';
import { analyzeChain } from './prefer-optional-chain-utils/analyzeChain';
import type { ValidOperand } from './prefer-optional-chain-utils/gatherLogicalOperands';
import {
gatherLogicalOperands,
OperandValidity,
} from './prefer-optional-chain-utils/gatherLogicalOperands';
import type {
PreferOptionalChainMessageIds,
PreferOptionalChainOptions,
} from './prefer-optional-chain-utils/PreferOptionalChainOptions';
export default createRule<
[PreferOptionalChainOptions],
PreferOptionalChainMessageIds
>({
name: 'prefer-optional-chain',
meta: {
type: 'suggestion',
docs: {
description:
'Enforce using concise optional chain expressions instead of chained logical ands, negated logical ors, or empty objects',
recommended: 'stylistic',
requiresTypeChecking: true,
},
fixable: 'code',
hasSuggestions: true,
messages: {
preferOptionalChain:
"Prefer using an optional chain expression instead, as it's more concise and easier to read.",
optionalChainSuggest: 'Change to an optional chain.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
checkAny: {
type: 'boolean',
description:
'Check operands that are typed as `any` when inspecting "loose boolean" operands.',
},
checkUnknown: {
type: 'boolean',
description:
'Check operands that are typed as `unknown` when inspecting "loose boolean" operands.',
},
checkString: {
type: 'boolean',
description:
'Check operands that are typed as `string` when inspecting "loose boolean" operands.',
},
checkNumber: {
type: 'boolean',
description:
'Check operands that are typed as `number` when inspecting "loose boolean" operands.',
},
checkBoolean: {
type: 'boolean',
description:
'Check operands that are typed as `boolean` when inspecting "loose boolean" operands.',
},
checkBigInt: {
type: 'boolean',
description:
'Check operands that are typed as `bigint` when inspecting "loose boolean" operands.',
},
requireNullish: {
type: 'boolean',
description:
'Skip operands that are not typed with `null` and/or `undefined` when inspecting "loose boolean" operands.',
},
allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing: {
type: 'boolean',
description:
'Allow autofixers that will change the return type of the expression. This option is considered unsafe as it may break the build.',
},
},
},
],
},
defaultOptions: [
{
checkAny: true,
checkUnknown: true,
checkString: true,
checkNumber: true,
checkBoolean: true,
checkBigInt: true,
requireNullish: false,
allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing: false,
},
],
create(context, [options]) {
const parserServices = getParserServices(context);
const seenLogicals = new Set<TSESTree.LogicalExpression>();
return {
// specific handling for `(foo ?? {}).bar` / `(foo || {}).bar`
'LogicalExpression[operator="||"], LogicalExpression[operator="??"]'(
node: TSESTree.LogicalExpression,
): void {
const leftNode = node.left;
const rightNode = node.right;
const parentNode = node.parent;
const isRightNodeAnEmptyObjectLiteral =
rightNode.type === AST_NODE_TYPES.ObjectExpression &&
rightNode.properties.length === 0;
if (
!isRightNodeAnEmptyObjectLiteral ||
parentNode.type !== AST_NODE_TYPES.MemberExpression ||
parentNode.optional
) {
return;
}
seenLogicals.add(node);
function isLeftSideLowerPrecedence(): boolean {
const logicalTsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const leftTsNode = parserServices.esTreeNodeToTSNodeMap.get(leftNode);
const operator = ts.isBinaryExpression(logicalTsNode)
? logicalTsNode.operatorToken.kind
: ts.SyntaxKind.Unknown;
const leftPrecedence = getOperatorPrecedence(
leftTsNode.kind,
operator,
);
return leftPrecedence < OperatorPrecedence.LeftHandSide;
}
context.report({
node: parentNode,
messageId: 'preferOptionalChain',
suggest: [
{
messageId: 'optionalChainSuggest',
fix: (fixer): RuleFix => {
const leftNodeText = context.sourceCode.getText(leftNode);
// Any node that is made of an operator with higher or equal precedence,
const maybeWrappedLeftNode = isLeftSideLowerPrecedence()
? `(${leftNodeText})`
: leftNodeText;
const propertyToBeOptionalText = context.sourceCode.getText(
parentNode.property,
);
const maybeWrappedProperty = parentNode.computed
? `[${propertyToBeOptionalText}]`
: propertyToBeOptionalText;
return fixer.replaceTextRange(
parentNode.range,
`${maybeWrappedLeftNode}?.${maybeWrappedProperty}`,
);
},
},
],
});
},
'LogicalExpression[operator!="??"]'(
node: TSESTree.LogicalExpression,
): void {
if (seenLogicals.has(node)) {
return;
}
const { operands, newlySeenLogicals } = gatherLogicalOperands(
node,
parserServices,
context.sourceCode,
options,
);
for (const logical of newlySeenLogicals) {
seenLogicals.add(logical);
}
let currentChain: ValidOperand[] = [];
for (const operand of operands) {
if (operand.type === OperandValidity.Invalid) {
analyzeChain(
context,
parserServices,
options,
node.operator,
currentChain,
);
currentChain = [];
} else {
currentChain.push(operand);
}
}
// make sure to check whatever's left
if (currentChain.length > 0) {
analyzeChain(
context,
parserServices,
options,
node.operator,
currentChain,
);
}
},
};
},
});