This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
/
strictComparisonsRule.ts
301 lines (271 loc) · 10.8 KB
/
strictComparisonsRule.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
/**
* @license
* Copyright 2019 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { isBinaryExpression, isTypeFlagSet, isUnionType } from "tsutils";
import * as ts from "typescript";
import * as Lint from "../index";
import { codeExamples } from "./code-examples/strictComparisons.examples";
const OPTION_ALLOW_OBJECT_EQUAL_COMPARISON = "allow-object-equal-comparison";
const OPTION_ALLOW_STRING_ORDER_COMPARISON = "allow-string-order-comparison";
const enum TypeKind {
Any = 0,
Number = 1,
Enum = 2,
String = 3,
Boolean = 4,
Null = 5,
Undefined = 6,
Object = 7,
}
const typeNames = {
[TypeKind.Any]: "any",
[TypeKind.Number]: "number",
[TypeKind.Enum]: "enum",
[TypeKind.String]: "string",
[TypeKind.Boolean]: "boolean",
[TypeKind.Null]: "null",
[TypeKind.Undefined]: "undefined",
[TypeKind.Object]: "object",
};
interface Options {
[OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]?: boolean;
[OPTION_ALLOW_STRING_ORDER_COMPARISON]?: boolean;
}
export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "strict-comparisons",
description: "Only allow comparisons between primitives.",
optionsDescription: Lint.Utils.dedent`
One of the following arguments may be optionally provided:
* \`${OPTION_ALLOW_OBJECT_EQUAL_COMPARISON}\` allows \`!=\` \`==\` \`!==\` \`===\` comparison between any types.
* \`${OPTION_ALLOW_STRING_ORDER_COMPARISON}\` allows \`>\` \`<\` \`>=\` \`<=\` comparison between strings.`,
options: {
type: "object",
properties: {
[OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]: {
type: "boolean",
},
[OPTION_ALLOW_STRING_ORDER_COMPARISON]: {
type: "boolean",
},
},
},
optionExamples: [
true,
[
true,
{
[OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]: false,
[OPTION_ALLOW_STRING_ORDER_COMPARISON]: false,
},
],
],
rationale: Lint.Utils.dedent`
When using comparison operators to compare objects, they compare references and not values.
This is often done accidentally.
With this rule, \`>\`, \`>=\`, \`<\`, \`<=\` operators are only allowed when comparing \`numbers\`.
\`===\`, \`!==\` are allowed for \`number\` \`string\` and \`boolean\` types and if one of the
operands is \`null\` or \`undefined\`.
`,
type: "functionality",
typescriptOnly: false,
requiresTypeInfo: true,
codeExamples,
};
/* tslint:enable:object-literal-sort-keys */
public static INVALID_TYPES(types1: TypeKind[], types2: TypeKind[]) {
const types1String = types1.map(type => typeNames[type]).join(" | ");
const types2String = types2.map(type => typeNames[type]).join(" | ");
return `Cannot compare type '${types1String}' to type '${types2String}'.`;
}
public static INVALID_TYPE_FOR_OPERATOR(type: TypeKind, comparator: string) {
return `Cannot use '${comparator}' comparator for type '${typeNames[type]}'.`;
}
public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk, this.getRuleOptions(), program);
}
private getRuleOptions(): Options {
if (this.ruleArguments[0] === undefined) {
return {};
} else {
return this.ruleArguments[0] as Options;
}
}
}
function walk(ctx: Lint.WalkContext<Options>, program: ts.Program) {
const { sourceFile, options } = ctx;
const checker = program.getTypeChecker();
return ts.forEachChild(sourceFile, function cb(node: ts.Node): void {
if (isBinaryExpression(node) && isComparisonOperator(node)) {
const isEquality = isEqualityOperator(node);
const leftType = checker.getTypeAtLocation(node.left);
const rightType = checker.getTypeAtLocation(node.right);
if (
(containsNullOrUndefined(leftType) || containsNullOrUndefined(rightType)) &&
isEquality
) {
return;
}
const leftKinds: TypeKind[] = getTypes(leftType);
const rightKinds: TypeKind[] = getTypes(rightType);
const operandKind = getStrictestComparableType(leftKinds, rightKinds);
if (operandKind === undefined) {
const failureString = Rule.INVALID_TYPES(leftKinds, rightKinds);
ctx.addFailureAtNode(node, failureString);
} else {
const failureString = Rule.INVALID_TYPE_FOR_OPERATOR(
operandKind,
node.operatorToken.getText(),
);
if (isEquality) {
// Check !=, ==, !==, ===
switch (operandKind) {
case TypeKind.Any:
case TypeKind.Number:
case TypeKind.Enum:
case TypeKind.String:
case TypeKind.Boolean:
break;
case TypeKind.Null:
case TypeKind.Undefined:
case TypeKind.Object:
if (options[OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]) {
break;
}
ctx.addFailureAtNode(node, failureString);
break;
default:
ctx.addFailureAtNode(node, failureString);
}
} else {
// Check >, <, >=, <=
switch (operandKind) {
case TypeKind.Any:
case TypeKind.Number:
break;
case TypeKind.String:
if (options[OPTION_ALLOW_STRING_ORDER_COMPARISON]) {
break;
}
ctx.addFailureAtNode(node, failureString);
break;
default:
ctx.addFailureAtNode(node, failureString);
}
}
}
}
return ts.forEachChild(node, cb);
});
}
function containsNullOrUndefined(type: ts.Type) {
return (
(type as ts.IntrinsicType).intrinsicName === "null" ||
(type as ts.IntrinsicType).intrinsicName === "undefined"
);
}
function getTypes(types: ts.Type): TypeKind[] {
// Compatibility for TypeScript pre-2.4, which used EnumLiteralType instead of LiteralType
const baseType = ((types as any) as { baseType: ts.LiteralType }).baseType;
return isUnionType(types)
? Array.from(new Set(types.types.map(getKind)))
: isTypeFlagSet(types, ts.TypeFlags.EnumLiteral) && typeof baseType !== "undefined"
? [getKind(baseType)]
: [getKind(types)];
}
function getStrictestComparableType(
typesLeft: TypeKind[],
typesRight: TypeKind[],
): TypeKind | undefined {
const overlappingTypes = typesLeft.filter(type => typesRight.indexOf(type) >= 0);
if (overlappingTypes.length > 0) {
return getStrictestKind(overlappingTypes);
} else {
// In case one of the types is "any", get the strictest type of the other array
if (arrayContainsKind(typesLeft, [TypeKind.Any])) {
return getStrictestKind(typesRight);
}
if (arrayContainsKind(typesRight, [TypeKind.Any])) {
return getStrictestKind(typesLeft);
}
// In case one array contains NullOrUndefined and the other an Object, return Object
if (
(arrayContainsKind(typesLeft, [TypeKind.Null, TypeKind.Undefined]) &&
arrayContainsKind(typesRight, [TypeKind.Object])) ||
(arrayContainsKind(typesRight, [TypeKind.Null, TypeKind.Undefined]) &&
arrayContainsKind(typesLeft, [TypeKind.Object]))
) {
return TypeKind.Object;
}
return undefined;
}
}
function arrayContainsKind(types: TypeKind[], typeToCheck: TypeKind[]): boolean {
return types.some(type => typeToCheck.indexOf(type) >= 0);
}
function getStrictestKind(types: TypeKind[]): TypeKind {
// tslint:disable-next-line:no-unsafe-any
return Math.max.apply(Math, types);
}
function isComparisonOperator(node: ts.BinaryExpression): boolean {
switch (node.operatorToken.kind) {
case ts.SyntaxKind.LessThanToken:
case ts.SyntaxKind.GreaterThanToken:
case ts.SyntaxKind.LessThanEqualsToken:
case ts.SyntaxKind.GreaterThanEqualsToken:
case ts.SyntaxKind.EqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsToken:
case ts.SyntaxKind.EqualsEqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
return true;
default:
return false;
}
}
function isEqualityOperator(node: ts.BinaryExpression): boolean {
switch (node.operatorToken.kind) {
case ts.SyntaxKind.EqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsToken:
case ts.SyntaxKind.EqualsEqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
return true;
default:
return false;
}
}
function getKind(type: ts.Type): TypeKind {
// tslint:disable:no-bitwise
if (is(ts.TypeFlags.String | ts.TypeFlags.StringLiteral)) {
return TypeKind.String;
} else if (is(ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) {
return TypeKind.Number;
} else if (is(ts.TypeFlags.BooleanLike)) {
return TypeKind.Boolean;
} else if (is(ts.TypeFlags.Null)) {
return TypeKind.Null;
} else if (is(ts.TypeFlags.Undefined)) {
return TypeKind.Undefined;
} else if (is(ts.TypeFlags.Any)) {
return TypeKind.Any;
} else {
return TypeKind.Object;
}
// tslint:enable:no-bitwise
function is(flags: ts.TypeFlags) {
return isTypeFlagSet(type, flags);
}
}