-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
no-unsafe-assignment.ts
402 lines (365 loc) · 12.1 KB
/
no-unsafe-assignment.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import * as tools from 'ts-api-utils';
import type * as ts from 'typescript';
import * as util from '../util';
import { getThisExpression } from '../util';
const enum ComparisonType {
/** Do no assignment comparison */
None,
/** Use the receiver's type for comparison */
Basic,
/** Use the sender's contextual type for comparison */
Contextual,
}
export default util.createRule({
name: 'no-unsafe-assignment',
meta: {
type: 'problem',
docs: {
description:
'Disallow assigning a value with type `any` to variables and properties',
recommended: 'error',
requiresTypeChecking: true,
},
messages: {
anyAssignment: 'Unsafe assignment of an `any` value.',
anyAssignmentThis: [
'Unsafe assignment of an `any` value. `this` is typed as `any`.',
'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.',
].join('\n'),
unsafeArrayPattern: 'Unsafe array destructuring of an `any` array value.',
unsafeArrayPatternFromTuple:
'Unsafe array destructuring of a tuple element with an `any` value.',
unsafeAssignment:
'Unsafe assignment of type {{sender}} to a variable of type {{receiver}}.',
unsafeArraySpread: 'Unsafe spread of an `any` value in an array.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = util.getParserServices(context);
const checker = services.program.getTypeChecker();
const compilerOptions = services.program.getCompilerOptions();
const isNoImplicitThis = tools.isStrictCompilerOptionEnabled(
compilerOptions,
'noImplicitThis',
);
// returns true if the assignment reported
function checkArrayDestructureHelper(
receiverNode: TSESTree.Node,
senderNode: TSESTree.Node,
): boolean {
if (receiverNode.type !== AST_NODE_TYPES.ArrayPattern) {
return false;
}
const senderTsNode = services.esTreeNodeToTSNodeMap.get(senderNode);
const senderType = services.getTypeAtLocation(senderNode);
return checkArrayDestructure(receiverNode, senderType, senderTsNode);
}
// returns true if the assignment reported
function checkArrayDestructure(
receiverNode: TSESTree.ArrayPattern,
senderType: ts.Type,
senderNode: ts.Node,
): boolean {
// any array
// const [x] = ([] as any[]);
if (util.isTypeAnyArrayType(senderType, checker)) {
context.report({
node: receiverNode,
messageId: 'unsafeArrayPattern',
});
return false;
}
if (!checker.isTupleType(senderType)) {
return true;
}
const tupleElements = util.getTypeArguments(senderType, checker);
// tuple with any
// const [x] = [1 as any];
let didReport = false;
for (
let receiverIndex = 0;
receiverIndex < receiverNode.elements.length;
receiverIndex += 1
) {
const receiverElement = receiverNode.elements[receiverIndex];
if (!receiverElement) {
continue;
}
if (receiverElement.type === AST_NODE_TYPES.RestElement) {
// don't handle rests as they're not a 1:1 assignment
continue;
}
const senderType = tupleElements[receiverIndex] as ts.Type | undefined;
if (!senderType) {
continue;
}
// check for the any type first so we can handle [[[x]]] = [any]
if (util.isTypeAnyType(senderType)) {
context.report({
node: receiverElement,
messageId: 'unsafeArrayPatternFromTuple',
});
// we want to report on every invalid element in the tuple
didReport = true;
} else if (receiverElement.type === AST_NODE_TYPES.ArrayPattern) {
didReport = checkArrayDestructure(
receiverElement,
senderType,
senderNode,
);
} else if (receiverElement.type === AST_NODE_TYPES.ObjectPattern) {
didReport = checkObjectDestructure(
receiverElement,
senderType,
senderNode,
);
}
}
return didReport;
}
// returns true if the assignment reported
function checkObjectDestructureHelper(
receiverNode: TSESTree.Node,
senderNode: TSESTree.Node,
): boolean {
if (receiverNode.type !== AST_NODE_TYPES.ObjectPattern) {
return false;
}
const senderTsNode = services.esTreeNodeToTSNodeMap.get(senderNode);
const senderType = services.getTypeAtLocation(senderNode);
return checkObjectDestructure(receiverNode, senderType, senderTsNode);
}
// returns true if the assignment reported
function checkObjectDestructure(
receiverNode: TSESTree.ObjectPattern,
senderType: ts.Type,
senderNode: ts.Node,
): boolean {
const properties = new Map(
senderType
.getProperties()
.map(property => [
property.getName(),
checker.getTypeOfSymbolAtLocation(property, senderNode),
]),
);
let didReport = false;
for (const receiverProperty of receiverNode.properties) {
if (receiverProperty.type === AST_NODE_TYPES.RestElement) {
// don't bother checking rest
continue;
}
let key: string;
if (receiverProperty.computed === false) {
key =
receiverProperty.key.type === AST_NODE_TYPES.Identifier
? receiverProperty.key.name
: String(receiverProperty.key.value);
} else if (receiverProperty.key.type === AST_NODE_TYPES.Literal) {
key = String(receiverProperty.key.value);
} else if (
receiverProperty.key.type === AST_NODE_TYPES.TemplateLiteral &&
receiverProperty.key.quasis.length === 1
) {
key = String(receiverProperty.key.quasis[0].value.cooked);
} else {
// can't figure out the name, so skip it
continue;
}
const senderType = properties.get(key);
if (!senderType) {
continue;
}
// check for the any type first so we can handle {x: {y: z}} = {x: any}
if (util.isTypeAnyType(senderType)) {
context.report({
node: receiverProperty.value,
messageId: 'unsafeArrayPatternFromTuple',
});
didReport = true;
} else if (
receiverProperty.value.type === AST_NODE_TYPES.ArrayPattern
) {
didReport = checkArrayDestructure(
receiverProperty.value,
senderType,
senderNode,
);
} else if (
receiverProperty.value.type === AST_NODE_TYPES.ObjectPattern
) {
didReport = checkObjectDestructure(
receiverProperty.value,
senderType,
senderNode,
);
}
}
return didReport;
}
// returns true if the assignment reported
function checkAssignment(
receiverNode: TSESTree.Node,
senderNode: TSESTree.Expression,
reportingNode: TSESTree.Node,
comparisonType: ComparisonType,
): boolean {
const receiverTsNode = services.esTreeNodeToTSNodeMap.get(receiverNode);
const receiverType =
comparisonType === ComparisonType.Contextual
? util.getContextualType(checker, receiverTsNode as ts.Expression) ??
services.getTypeAtLocation(receiverNode)
: services.getTypeAtLocation(receiverNode);
const senderType = services.getTypeAtLocation(senderNode);
if (util.isTypeAnyType(senderType)) {
// handle cases when we assign any ==> unknown.
if (util.isTypeUnknownType(receiverType)) {
return false;
}
let messageId: 'anyAssignment' | 'anyAssignmentThis' = 'anyAssignment';
if (!isNoImplicitThis) {
// `var foo = this`
const thisExpression = getThisExpression(senderNode);
if (
thisExpression &&
util.isTypeAnyType(
util.getConstrainedTypeAtLocation(services, thisExpression),
)
) {
messageId = 'anyAssignmentThis';
}
}
context.report({
node: reportingNode,
messageId,
});
return true;
}
if (comparisonType === ComparisonType.None) {
return false;
}
const result = util.isUnsafeAssignment(
senderType,
receiverType,
checker,
senderNode,
);
if (!result) {
return false;
}
const { sender, receiver } = result;
context.report({
node: reportingNode,
messageId: 'unsafeAssignment',
data: {
sender: checker.typeToString(sender),
receiver: checker.typeToString(receiver),
},
});
return true;
}
function getComparisonType(
typeAnnotation: TSESTree.TSTypeAnnotation | undefined,
): ComparisonType {
return typeAnnotation
? // if there's a type annotation, we can do a comparison
ComparisonType.Basic
: // no type annotation means the variable's type will just be inferred, thus equal
ComparisonType.None;
}
return {
'VariableDeclarator[init != null]'(
node: TSESTree.VariableDeclarator,
): void {
const init = util.nullThrows(
node.init,
util.NullThrowsReasons.MissingToken(node.type, 'init'),
);
let didReport = checkAssignment(
node.id,
init,
node,
getComparisonType(node.id.typeAnnotation),
);
if (!didReport) {
didReport = checkArrayDestructureHelper(node.id, init);
}
if (!didReport) {
checkObjectDestructureHelper(node.id, init);
}
},
'PropertyDefinition[value != null]'(
node: TSESTree.PropertyDefinition,
): void {
checkAssignment(
node.key,
node.value!,
node,
getComparisonType(node.typeAnnotation),
);
},
'AssignmentExpression[operator = "="], AssignmentPattern'(
node: TSESTree.AssignmentExpression | TSESTree.AssignmentPattern,
): void {
let didReport = checkAssignment(
node.left,
node.right,
node,
// the variable already has some form of a type to compare against
ComparisonType.Basic,
);
if (!didReport) {
didReport = checkArrayDestructureHelper(node.left, node.right);
}
if (!didReport) {
checkObjectDestructureHelper(node.left, node.right);
}
},
// object pattern props are checked via assignments
':not(ObjectPattern) > Property'(node: TSESTree.Property): void {
if (
node.value.type === AST_NODE_TYPES.AssignmentPattern ||
node.value.type === AST_NODE_TYPES.TSEmptyBodyFunctionExpression
) {
// handled by other selector
return;
}
checkAssignment(node.key, node.value, node, ComparisonType.Contextual);
},
'ArrayExpression > SpreadElement'(node: TSESTree.SpreadElement): void {
const restType = services.getTypeAtLocation(node.argument);
if (
util.isTypeAnyType(restType) ||
util.isTypeAnyArrayType(restType, checker)
) {
context.report({
node: node,
messageId: 'unsafeArraySpread',
});
}
},
'JSXAttribute[value != null]'(node: TSESTree.JSXAttribute): void {
const value = util.nullThrows(
node.value,
util.NullThrowsReasons.MissingToken(node.type, 'value'),
);
if (
value.type !== AST_NODE_TYPES.JSXExpressionContainer ||
value.expression.type === AST_NODE_TYPES.JSXEmptyExpression
) {
return;
}
checkAssignment(
node.name,
value.expression,
value.expression,
ComparisonType.Contextual,
);
},
};
},
});