This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
/
noPromiseAsBooleanRule.ts
163 lines (145 loc) · 6.2 KB
/
noPromiseAsBooleanRule.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
/**
* @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,
isConditionalExpression,
isDoStatement,
isForStatement,
isIfStatement,
isPrefixUnaryExpression,
isUnionType,
isWhileStatement,
} from "tsutils";
import * as ts from "typescript";
import * as Lint from "../index";
import { codeExamples } from "./code-examples/noPromiseAsBoolean.examples";
const OPTION_PROMISE_CLASSES = "promise-classes";
interface Options {
promiseClasses: string[];
}
export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "no-promise-as-boolean",
description: "Warns for Promises that are used for boolean conditions.",
descriptionDetails: Lint.Utils.dedent`
For the most accurate findings, set \`"strict": true\` in your \`tsconfig.json\`.
It's recommended to enable the following rules as well:
* [\`strict-boolean-expressions\`](https://palantir.github.io/tslint/rules/strict-boolean-expressions/)
* [\`strict-type-predicates\`](https://palantir.github.io/tslint/rules/strict-type-predicates/)
* [\`no-floating-promises\`](https://palantir.github.io/tslint/rules/no-floating-promises/)
`,
optionsDescription: Lint.Utils.dedent`
A list of 'string' names of any additional classes that should also be treated as Promises.
For example, if you are using a class called 'Future' that implements the Thenable interface,
you might tell the rule to consider type references with the name 'Future' as valid Promise-like
types. Note that this rule doesn't check for type assignability or compatibility; it just checks
type reference names.
`,
options: {
type: "object",
properties: {
[OPTION_PROMISE_CLASSES]: {
type: "array",
items: { type: "string" },
},
},
},
optionExamples: [true, [true, { OPTION_PROMISE_CLASSES: ["Thenable"] }]],
rationale: Lint.Utils.dedent`
There are no situations where one would like to check whether a variable's value is truthy if its type
only is Promise.
This may only occur when the typings are incorrect or the variable has a union type
(like Promise | undefined), of which the latter is allowed.
This rule prevents common bugs from forgetting to 'await' a Promise.
`,
type: "functionality",
typescriptOnly: true,
requiresTypeInfo: true,
codeExamples,
};
/* tslint:enable:object-literal-sort-keys */
public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
// tslint:disable-next-line: no-object-literal-type-assertion
const rawOptions = { ...this.ruleArguments[0] } as { [OPTION_PROMISE_CLASSES]?: string[] };
const promiseClasses =
rawOptions[OPTION_PROMISE_CLASSES] !== undefined
? rawOptions[OPTION_PROMISE_CLASSES]!
: [];
return this.applyWithFunction(
sourceFile,
walk,
{ promiseClasses: ["Promise", ...promiseClasses] },
program.getTypeChecker(),
);
}
}
const RULE_MESSAGE = "Promises are not allowed as boolean.";
function walk(context: Lint.WalkContext<Options>, checker: ts.TypeChecker): void {
const { sourceFile } = context;
return ts.forEachChild(sourceFile, cb);
function cb(node: ts.Node): void {
if (isBooleanBinaryExpression(node)) {
const { left, right } = node;
if (!isBooleanBinaryExpression(left)) {
checkExpression(left);
}
if (!isBooleanBinaryExpression(right)) {
checkExpression(right);
}
} else if (isPrefixUnaryExpression(node)) {
const { operator, operand } = node;
if (operator === ts.SyntaxKind.ExclamationToken) {
checkExpression(operand);
}
} else if (isIfStatement(node) || isWhileStatement(node) || isDoStatement(node)) {
// If it's a boolean binary expression, we'll check it when recursing.
if (!isBooleanBinaryExpression(node.expression)) {
checkExpression(node.expression);
}
} else if (isConditionalExpression(node)) {
checkExpression(node.condition);
} else if (isForStatement(node)) {
const { condition } = node;
if (condition !== undefined) {
checkExpression(condition);
}
}
return ts.forEachChild(node, cb);
}
function checkExpression(expression: ts.Expression): void {
const mainType = checker.getTypeAtLocation(expression);
if (
isPromiseType(mainType) ||
(isUnionType(mainType) && mainType.types.every(isPromiseType))
) {
context.addFailureAtNode(expression, RULE_MESSAGE);
}
}
function isPromiseType(type: ts.Type) {
const promiseClasses = context.options.promiseClasses;
return type.symbol !== undefined && promiseClasses.indexOf(type.symbol.name) !== -1;
}
}
/** Matches `&&` and `||` operators. */
function isBooleanBinaryExpression(expression: ts.Node): expression is ts.BinaryExpression {
return (
isBinaryExpression(expression) &&
(expression.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
expression.operatorToken.kind === ts.SyntaxKind.BarBarToken)
);
}