forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefer-destructuring.ts
237 lines (219 loc) · 6.46 KB
/
prefer-destructuring.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { JSONSchema4 } from '@typescript-eslint/utils/json-schema';
import * as tsutils from 'ts-api-utils';
import type * as ts from 'typescript';
import type {
InferMessageIdsTypeFromRule,
InferOptionsTypeFromRule,
} from '../util';
import { createRule, getParserServices, isTypeAnyType } from '../util';
import { getESLintCoreRule } from '../util/getESLintCoreRule';
const baseRule = getESLintCoreRule('prefer-destructuring');
type BaseOptions = InferOptionsTypeFromRule<typeof baseRule>;
type EnforcementOptions = BaseOptions[1] & {
enforceForDeclarationWithTypeAnnotation?: boolean;
};
type Options = [BaseOptions[0], EnforcementOptions];
type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;
const destructuringTypeConfig: JSONSchema4 = {
type: 'object',
properties: {
array: {
type: 'boolean',
},
object: {
type: 'boolean',
},
},
additionalProperties: false,
};
const schema: readonly JSONSchema4[] = [
{
oneOf: [
{
type: 'object',
properties: {
VariableDeclarator: destructuringTypeConfig,
AssignmentExpression: destructuringTypeConfig,
},
additionalProperties: false,
},
destructuringTypeConfig,
],
},
{
type: 'object',
properties: {
enforceForRenamedProperties: {
type: 'boolean',
},
enforceForDeclarationWithTypeAnnotation: {
type: 'boolean',
},
},
},
];
export default createRule<Options, MessageIds>({
name: 'prefer-destructuring',
meta: {
type: 'suggestion',
docs: {
description: 'Require destructuring from arrays and/or objects',
extendsBaseRule: true,
requiresTypeChecking: true,
},
schema,
fixable: baseRule.meta.fixable,
hasSuggestions: baseRule.meta.hasSuggestions,
messages: baseRule.meta.messages,
},
defaultOptions: [
{
VariableDeclarator: {
array: true,
object: true,
},
AssignmentExpression: {
array: true,
object: true,
},
},
{},
],
create(context, [enabledTypes, options]) {
const {
enforceForRenamedProperties = false,
enforceForDeclarationWithTypeAnnotation = false,
} = options;
const { program, esTreeNodeToTSNodeMap } = getParserServices(context);
const typeChecker = program.getTypeChecker();
const baseRules = baseRule.create(context);
let baseRulesWithoutFixCache: typeof baseRules | null = null;
return {
VariableDeclarator(node): void {
performCheck(node.id, node.init, node);
},
AssignmentExpression(node): void {
if (node.operator !== '=') {
return;
}
performCheck(node.left, node.right, node);
},
};
function performCheck(
leftNode: TSESTree.BindingName | TSESTree.Expression,
rightNode: TSESTree.Expression | null,
reportNode: TSESTree.VariableDeclarator | TSESTree.AssignmentExpression,
): void {
const rules =
leftNode.type === AST_NODE_TYPES.Identifier &&
leftNode.typeAnnotation === undefined
? baseRules
: baseRulesWithoutFix();
if (
'typeAnnotation' in leftNode &&
leftNode.typeAnnotation !== undefined &&
!enforceForDeclarationWithTypeAnnotation
) {
return;
}
if (
rightNode != null &&
isArrayLiteralIntegerIndexAccess(rightNode) &&
rightNode.object.type !== AST_NODE_TYPES.Super
) {
const tsObj = esTreeNodeToTSNodeMap.get(rightNode.object);
const objType = typeChecker.getTypeAtLocation(tsObj);
if (!isTypeAnyOrIterableType(objType, typeChecker)) {
if (
!enforceForRenamedProperties ||
!getNormalizedEnabledType(reportNode.type, 'object')
) {
return;
}
context.report({
node: reportNode,
messageId: 'preferDestructuring',
data: { type: 'object' },
});
return;
}
}
if (reportNode.type === AST_NODE_TYPES.AssignmentExpression) {
rules.AssignmentExpression(reportNode);
} else {
rules.VariableDeclarator(reportNode);
}
}
function getNormalizedEnabledType(
nodeType:
| AST_NODE_TYPES.VariableDeclarator
| AST_NODE_TYPES.AssignmentExpression,
destructuringType: 'array' | 'object',
): boolean | undefined {
if ('object' in enabledTypes || 'array' in enabledTypes) {
return enabledTypes[destructuringType];
}
return enabledTypes[nodeType as keyof typeof enabledTypes][
destructuringType as keyof (typeof enabledTypes)[keyof typeof enabledTypes]
];
}
function baseRulesWithoutFix(): ReturnType<typeof baseRule.create> {
baseRulesWithoutFixCache ??= baseRule.create(noFixContext(context));
return baseRulesWithoutFixCache;
}
},
});
type Context = TSESLint.RuleContext<MessageIds, Options>;
function noFixContext(context: Context): Context {
const customContext: {
report: Context['report'];
} = {
report: (descriptor): void => {
context.report({
...descriptor,
fix: undefined,
});
},
};
// we can't directly proxy `context` because its `report` property is non-configurable
// and non-writable. So we proxy `customContext` and redirect all
// property access to the original context except for `report`
return new Proxy<Context>(customContext as typeof context, {
get(target, path, receiver): unknown {
if (path !== 'report') {
return Reflect.get(context, path, receiver);
}
return Reflect.get(target, path, receiver);
},
});
}
function isTypeAnyOrIterableType(
type: ts.Type,
typeChecker: ts.TypeChecker,
): boolean {
if (isTypeAnyType(type)) {
return true;
}
if (!type.isUnion()) {
const iterator = tsutils.getWellKnownSymbolPropertyOfType(
type,
'iterator',
typeChecker,
);
return iterator !== undefined;
}
return type.types.every(t => isTypeAnyOrIterableType(t, typeChecker));
}
function isArrayLiteralIntegerIndexAccess(
node: TSESTree.Expression,
): node is TSESTree.MemberExpression {
if (node.type !== AST_NODE_TYPES.MemberExpression) {
return false;
}
if (node.property.type !== AST_NODE_TYPES.Literal) {
return false;
}
return Number.isInteger(node.property.value);
}