4 * Copyright 2019 Palantir Technologies, Inc.
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 Object.defineProperty(exports, "__esModule", { value: true });
19 var tslib_1 = require("tslib");
21 var tsutils_1 = require("tsutils");
22 var ts = require("typescript");
23 var Lint = require("../index");
24 var noPromiseAsBoolean_examples_1 = require("./code-examples/noPromiseAsBoolean.examples");
25 var OPTION_PROMISE_CLASSES = "promise-classes";
26 var Rule = /** @class */ (function (_super) {
27 tslib_1.__extends(Rule, _super);
29 return _super !== null && _super.apply(this, arguments) || this;
31 /* tslint:enable:object-literal-sort-keys */
32 Rule.prototype.applyWithProgram = function (sourceFile, program) {
33 // tslint:disable-next-line: no-object-literal-type-assertion
34 var rawOptions = tslib_1.__assign({}, this.ruleArguments[0]);
35 var promiseClasses = rawOptions[OPTION_PROMISE_CLASSES] !== undefined
36 ? rawOptions[OPTION_PROMISE_CLASSES]
38 return this.applyWithFunction(sourceFile, walk, { promiseClasses: ["Promise"].concat(promiseClasses) }, program.getTypeChecker());
40 /* tslint:disable:object-literal-sort-keys */
42 ruleName: "no-promise-as-boolean",
43 description: "Warns for Promises that are used for boolean conditions.",
44 descriptionDetails: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n For the most accurate findings, set `\"strict\": true` in your `tsconfig.json`.\n\n It's recommended to enable the following rules as well:\n * [`strict-boolean-expressions`](https://palantir.github.io/tslint/rules/strict-boolean-expressions/)\n * [`strict-type-predicates`](https://palantir.github.io/tslint/rules/strict-type-predicates/)\n * [`no-floating-promises`](https://palantir.github.io/tslint/rules/no-floating-promises/)\n "], ["\n For the most accurate findings, set \\`\"strict\": true\\` in your \\`tsconfig.json\\`.\n\n It's recommended to enable the following rules as well:\n * [\\`strict-boolean-expressions\\`](https://palantir.github.io/tslint/rules/strict-boolean-expressions/)\n * [\\`strict-type-predicates\\`](https://palantir.github.io/tslint/rules/strict-type-predicates/)\n * [\\`no-floating-promises\\`](https://palantir.github.io/tslint/rules/no-floating-promises/)\n "]))),
45 optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n A list of 'string' names of any additional classes that should also be treated as Promises.\n For example, if you are using a class called 'Future' that implements the Thenable interface,\n you might tell the rule to consider type references with the name 'Future' as valid Promise-like\n types. Note that this rule doesn't check for type assignability or compatibility; it just checks\n type reference names.\n "], ["\n A list of 'string' names of any additional classes that should also be treated as Promises.\n For example, if you are using a class called 'Future' that implements the Thenable interface,\n you might tell the rule to consider type references with the name 'Future' as valid Promise-like\n types. Note that this rule doesn't check for type assignability or compatibility; it just checks\n type reference names.\n "]))),
49 _a[OPTION_PROMISE_CLASSES] = {
51 items: { type: "string" },
55 optionExamples: [true, [true, { OPTION_PROMISE_CLASSES: ["Thenable"] }]],
56 rationale: Lint.Utils.dedent(templateObject_3 || (templateObject_3 = tslib_1.__makeTemplateObject(["\n There are no situations where one would like to check whether a variable's value is truthy if its type\n only is Promise.\n This may only occur when the typings are incorrect or the variable has a union type\n (like Promise | undefined), of which the latter is allowed.\n\n This rule prevents common bugs from forgetting to 'await' a Promise.\n "], ["\n There are no situations where one would like to check whether a variable's value is truthy if its type\n only is Promise.\n This may only occur when the typings are incorrect or the variable has a union type\n (like Promise | undefined), of which the latter is allowed.\n\n This rule prevents common bugs from forgetting to 'await' a Promise.\n "]))),
57 type: "functionality",
59 requiresTypeInfo: true,
60 codeExamples: noPromiseAsBoolean_examples_1.codeExamples,
63 }(Lint.Rules.TypedRule));
65 var RULE_MESSAGE = "Promises are not allowed as boolean.";
66 function walk(context, checker) {
67 var sourceFile = context.sourceFile;
68 return ts.forEachChild(sourceFile, cb);
70 if (isBooleanBinaryExpression(node)) {
71 var left = node.left, right = node.right;
72 if (!isBooleanBinaryExpression(left)) {
73 checkExpression(left);
75 if (!isBooleanBinaryExpression(right)) {
76 checkExpression(right);
79 else if (tsutils_1.isPrefixUnaryExpression(node)) {
80 var operator = node.operator, operand = node.operand;
81 if (operator === ts.SyntaxKind.ExclamationToken) {
82 checkExpression(operand);
85 else if (tsutils_1.isIfStatement(node) || tsutils_1.isWhileStatement(node) || tsutils_1.isDoStatement(node)) {
86 // If it's a boolean binary expression, we'll check it when recursing.
87 if (!isBooleanBinaryExpression(node.expression)) {
88 checkExpression(node.expression);
91 else if (tsutils_1.isConditionalExpression(node)) {
92 checkExpression(node.condition);
94 else if (tsutils_1.isForStatement(node)) {
95 var condition = node.condition;
96 if (condition !== undefined) {
97 checkExpression(condition);
100 return ts.forEachChild(node, cb);
102 function checkExpression(expression) {
103 var mainType = checker.getTypeAtLocation(expression);
104 if (isPromiseType(mainType) ||
105 (tsutils_1.isUnionType(mainType) && mainType.types.every(isPromiseType))) {
106 context.addFailureAtNode(expression, RULE_MESSAGE);
109 function isPromiseType(type) {
110 var promiseClasses = context.options.promiseClasses;
111 return type.symbol !== undefined && promiseClasses.indexOf(type.symbol.name) !== -1;
114 /** Matches `&&` and `||` operators. */
115 function isBooleanBinaryExpression(expression) {
116 return (tsutils_1.isBinaryExpression(expression) &&
117 (expression.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
118 expression.operatorToken.kind === ts.SyntaxKind.BarBarToken));
120 var templateObject_1, templateObject_2, templateObject_3;