This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
/
strictTypePredicatesRule.ts
264 lines (230 loc) · 9.82 KB
/
strictTypePredicatesRule.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
/**
* @license
* Copyright 2017 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, isUnionType } from "tsutils";
import * as ts from "typescript";
import { showWarningOnce } from "../error";
import * as Lint from "../index";
// tslint:disable:no-bitwise
export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "strict-type-predicates",
description: Lint.Utils.dedent`
Warns for type predicates that are always true or always false.
Works for 'typeof' comparisons to constants (e.g. 'typeof foo === "string"'), and equality comparison to 'null'/'undefined'.
(TypeScript won't let you compare '1 === 2', but it has an exception for '1 === undefined'.)
Does not yet work for 'instanceof'.
Does *not* warn for 'if (x.y)' where 'x.y' is always truthy. For that, see strict-boolean-expressions.
This rule requires \`strictNullChecks\` to work properly.`,
optionsDescription: "Not configurable.",
options: null,
optionExamples: [true],
type: "functionality",
typescriptOnly: true,
requiresTypeInfo: true,
};
/* tslint:enable:object-literal-sort-keys */
public static FAILURE_STRING_BAD_TYPEOF = "Bad comparison for 'typeof'.";
public static FAILURE_STRING(value: boolean): string {
return `Expression is always ${value}.`;
}
public static FAILURE_STRICT_PREFER_STRICT_EQUALS(value: "null" | "undefined", isPositive: boolean) {
return `Use '${isPositive ? "===" : "!=="} ${value}' instead.`;
}
public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
if (!Lint.isStrictNullChecksEnabled(program.getCompilerOptions())) {
showWarningOnce("strict-type-predicates does not work without strictNullChecks");
return [];
}
return this.applyWithFunction(sourceFile, (ctx) => walk(ctx, program.getTypeChecker()));
}
}
function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isBinaryExpression(node)) {
const equals = Lint.getEqualsKind(node.operatorToken);
if (equals !== undefined) {
checkEquals(node, equals);
}
}
return ts.forEachChild(node, cb);
});
function checkEquals(node: ts.BinaryExpression, { isStrict, isPositive }: Lint.EqualsKind): void {
const exprPred = getTypePredicate(node, isStrict);
if (exprPred === undefined) {
return;
}
if (exprPred.kind === TypePredicateKind.TypeofTypo) {
fail(Rule.FAILURE_STRING_BAD_TYPEOF);
return;
}
const exprType = checker.getTypeAtLocation(exprPred.expression);
// TODO: could use checker.getBaseConstraintOfType to help with type parameters, but it's not publicly exposed.
if (Lint.isTypeFlagSet(exprType, ts.TypeFlags.Any | ts.TypeFlags.TypeParameter)) {
return;
}
switch (exprPred.kind) {
case TypePredicateKind.Plain: {
const { predicate, isNullOrUndefined } = exprPred;
const value = getConstantBoolean(exprType, predicate);
// 'null'/'undefined' are the only two values *not* assignable to '{}'.
if (value !== undefined && (isNullOrUndefined || !isEmptyType(checker, exprType))) {
fail(Rule.FAILURE_STRING(value === isPositive));
}
break;
}
case TypePredicateKind.NonStructNullUndefined: {
const result = testNonStrictNullUndefined(exprType);
if (result !== undefined) {
fail(typeof result === "boolean"
? Rule.FAILURE_STRING(result === isPositive)
: Rule.FAILURE_STRICT_PREFER_STRICT_EQUALS(result, isPositive));
}
break;
}
}
function fail(failure: string): void {
ctx.addFailureAtNode(node, failure);
}
}
}
/** Detects a type predicate given `left === right`. */
function getTypePredicate(node: ts.BinaryExpression, isStrictEquals: boolean): TypePredicate | undefined {
const { left, right } = node;
const lr = getTypePredicateOneWay(left, right, isStrictEquals);
return lr !== undefined ? lr : getTypePredicateOneWay(right, left, isStrictEquals);
}
/** Only gets the type predicate if the expression is on the left. */
function getTypePredicateOneWay(left: ts.Expression, right: ts.Expression, isStrictEquals: boolean): TypePredicate | undefined {
switch (right.kind) {
case ts.SyntaxKind.TypeOfExpression:
const expression = (right as ts.TypeOfExpression).expression;
const kind = left.kind === ts.SyntaxKind.StringLiteral ? (left as ts.StringLiteral).text : "";
const predicate = getTypePredicateForKind(kind);
return predicate === undefined
? { kind: TypePredicateKind.TypeofTypo }
: { kind: TypePredicateKind.Plain, expression, predicate, isNullOrUndefined: kind === "undefined" };
case ts.SyntaxKind.NullKeyword:
return nullOrUndefined(ts.TypeFlags.Null);
case ts.SyntaxKind.Identifier:
if ((right as ts.Identifier).originalKeywordKind === ts.SyntaxKind.UndefinedKeyword) {
return nullOrUndefined(undefinedFlags);
}
return undefined;
default:
return undefined;
}
function nullOrUndefined(flags: ts.TypeFlags): TypePredicate {
return isStrictEquals
? { kind: TypePredicateKind.Plain, expression: left, predicate: flagPredicate(flags), isNullOrUndefined: true }
: { kind: TypePredicateKind.NonStructNullUndefined, expression: left };
}
}
function isEmptyType(checker: ts.TypeChecker, type: ts.Type) {
return checker.typeToString(type) === "{}";
}
const undefinedFlags = ts.TypeFlags.Undefined | ts.TypeFlags.Void;
type TypePredicate = PlainTypePredicate | NonStrictNullUndefinedPredicate | { kind: TypePredicateKind.TypeofTypo };
interface PlainTypePredicate {
kind: TypePredicateKind.Plain;
expression: ts.Expression;
predicate: Predicate;
isNullOrUndefined: boolean;
}
/** For `== null` and the like. */
interface NonStrictNullUndefinedPredicate {
kind: TypePredicateKind.NonStructNullUndefined;
expression: ts.Expression;
}
const enum TypePredicateKind {
Plain,
NonStructNullUndefined,
TypeofTypo,
}
type Predicate = (type: ts.Type) => boolean;
function getTypePredicateForKind(kind: string): Predicate | undefined {
switch (kind) {
case "undefined":
return flagPredicate(undefinedFlags);
case "boolean":
return flagPredicate(ts.TypeFlags.BooleanLike);
case "number":
return flagPredicate(ts.TypeFlags.NumberLike);
case "string":
return flagPredicate(ts.TypeFlags.StringLike);
case "symbol":
return flagPredicate(ts.TypeFlags.ESSymbol);
case "function":
return isFunction;
case "object":
// It's an object if it's not any of the above.
const allFlags = ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.BooleanLike |
ts.TypeFlags.NumberLike | ts.TypeFlags.StringLike | ts.TypeFlags.ESSymbol;
return (type) => !Lint.isTypeFlagSet(type, allFlags) && !isFunction(type);
default:
return undefined;
}
}
function flagPredicate(testedFlag: ts.TypeFlags): Predicate {
return (type) => Lint.isTypeFlagSet(type, testedFlag);
}
function isFunction(t: ts.Type): boolean {
if (t.getConstructSignatures().length !== 0 || t.getCallSignatures().length !== 0) {
return true;
}
const symbol = t.getSymbol();
return symbol !== undefined && symbol.getName() === "Function";
}
/** Returns a boolean value if that should always be the result of a type predicate. */
function getConstantBoolean(type: ts.Type, predicate: (t: ts.Type) => boolean): boolean | undefined {
let anyTrue = false;
let anyFalse = false;
for (const ty of unionParts(type)) {
if (predicate(ty)) {
anyTrue = true;
} else {
anyFalse = true;
}
if (anyTrue && anyFalse) {
return undefined;
}
}
return anyTrue;
}
/** Returns bool for always/never true, or a string to recommend strict equality. */
function testNonStrictNullUndefined(type: ts.Type): boolean | "null" | "undefined" | undefined {
let anyNull = false;
let anyUndefined = false;
let anyOther = false;
for (const ty of unionParts(type)) {
if (Lint.isTypeFlagSet(ty, ts.TypeFlags.Null)) {
anyNull = true;
} else if (Lint.isTypeFlagSet(ty, undefinedFlags)) {
anyUndefined = true;
} else {
anyOther = true;
}
}
return !anyOther ? true
: anyNull && anyUndefined ? undefined
: anyNull ? "null"
: anyUndefined ? "undefined"
: false;
}
function unionParts(type: ts.Type) {
return isUnionType(type) ? type.types : [type];
}