4 * Copyright 2018 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");
20 var tsutils_1 = require("tsutils");
21 var ts = require("typescript");
22 var Lint = require("../index");
23 var OPTION_ALLOW_NULL_UNION = "allow-null-union";
24 var OPTION_ALLOW_UNDEFINED_UNION = "allow-undefined-union";
25 var OPTION_ALLOW_STRING = "allow-string";
26 var OPTION_ALLOW_ENUM = "allow-enum";
27 var OPTION_ALLOW_NUMBER = "allow-number";
28 var OPTION_ALLOW_MIX = "allow-mix";
29 var OPTION_ALLOW_BOOLEAN_OR_UNDEFINED = "allow-boolean-or-undefined";
30 var OPTION_IGNORE_RHS = "ignore-rhs";
31 // tslint:disable object-literal-sort-keys no-bitwise
32 var Rule = /** @class */ (function (_super) {
33 tslib_1.__extends(Rule, _super);
35 return _super !== null && _super.apply(this, arguments) || this;
37 Rule.prototype.applyWithProgram = function (sourceFile, program) {
38 var options = parseOptions(this.ruleArguments, Lint.isStrictNullChecksEnabled(program.getCompilerOptions()));
39 return this.applyWithFunction(sourceFile, walk, options, program.getTypeChecker());
42 ruleName: "strict-boolean-expressions",
43 description: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Restricts the types allowed in boolean expressions. By default only booleans are allowed.\n\n The following nodes are checked:\n\n * Arguments to the `!`, `&&`, and `||` operators\n * The condition in a conditional expression (`cond ? x : y`)\n * Conditions for `if`, `for`, `while`, and `do-while` statements."], ["\n Restricts the types allowed in boolean expressions. By default only booleans are allowed.\n\n The following nodes are checked:\n\n * Arguments to the \\`!\\`, \\`&&\\`, and \\`||\\` operators\n * The condition in a conditional expression (\\`cond ? x : y\\`)\n * Conditions for \\`if\\`, \\`for\\`, \\`while\\`, and \\`do-while\\` statements."]))),
44 optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n These options may be provided:\n\n * `", "` allows union types containing `null`.\n - It does *not* allow `null` itself.\n - Without the '--strictNullChecks' compiler option, this will allow anything other than a string, number, or enum.\n * `", "` allows union types containing `undefined`.\n - It does *not* allow `undefined` itself.\n - Without the '--strictNullChecks' compiler option, this will allow anything other than a string, number, or enum.\n * `", "` allows strings.\n - It does *not* allow unions containing `string`.\n - It does *not* allow string literal types.\n * `", "` allows enums.\n - It does *not* allow unions containing `enum`.\n * `", "` allows numbers.\n - It does *not* allow unions containing `number`.\n - It does *not* allow enums or number literal types.\n * `", "` allows multiple of the above to appear together.\n - For example, `string | number` or `RegExp | null | undefined` would normally not be allowed.\n - A type like `\"foo\" | \"bar\" | undefined` is always allowed, because it has only one way to be false.\n * `", "` allows `boolean | undefined`.\n - Also allows `true | false | undefined`.\n - Does not allow `false | undefined`.\n - This option is a subset of `", "`, so you don't need to enable both options at the same time.\n * `", "` ignores the right-hand operand of `&&` and `||`.\n "], ["\n These options may be provided:\n\n * \\`", "\\` allows union types containing \\`null\\`.\n - It does *not* allow \\`null\\` itself.\n - Without the '--strictNullChecks' compiler option, this will allow anything other than a string, number, or enum.\n * \\`", "\\` allows union types containing \\`undefined\\`.\n - It does *not* allow \\`undefined\\` itself.\n - Without the '--strictNullChecks' compiler option, this will allow anything other than a string, number, or enum.\n * \\`", "\\` allows strings.\n - It does *not* allow unions containing \\`string\\`.\n - It does *not* allow string literal types.\n * \\`", "\\` allows enums.\n - It does *not* allow unions containing \\`enum\\`.\n * \\`", "\\` allows numbers.\n - It does *not* allow unions containing \\`number\\`.\n - It does *not* allow enums or number literal types.\n * \\`", "\\` allows multiple of the above to appear together.\n - For example, \\`string | number\\` or \\`RegExp | null | undefined\\` would normally not be allowed.\n - A type like \\`\"foo\" | \"bar\" | undefined\\` is always allowed, because it has only one way to be false.\n * \\`", "\\` allows \\`boolean | undefined\\`.\n - Also allows \\`true | false | undefined\\`.\n - Does not allow \\`false | undefined\\`.\n - This option is a subset of \\`", "\\`, so you don't need to enable both options at the same time.\n * \\`", "\\` ignores the right-hand operand of \\`&&\\` and \\`||\\`.\n "])), OPTION_ALLOW_NULL_UNION, OPTION_ALLOW_UNDEFINED_UNION, OPTION_ALLOW_STRING, OPTION_ALLOW_ENUM, OPTION_ALLOW_NUMBER, OPTION_ALLOW_MIX, OPTION_ALLOW_BOOLEAN_OR_UNDEFINED, OPTION_ALLOW_UNDEFINED_UNION, OPTION_IGNORE_RHS),
50 OPTION_ALLOW_NULL_UNION,
51 OPTION_ALLOW_UNDEFINED_UNION,
55 OPTION_ALLOW_BOOLEAN_OR_UNDEFINED,
66 OPTION_ALLOW_NULL_UNION,
67 OPTION_ALLOW_UNDEFINED_UNION,
72 [true, OPTION_ALLOW_BOOLEAN_OR_UNDEFINED],
74 type: "functionality",
76 requiresTypeInfo: true,
79 }(Lint.Rules.TypedRule));
81 function parseOptions(ruleArguments, strictNullChecks) {
83 strictNullChecks: strictNullChecks,
84 allowNullUnion: has(OPTION_ALLOW_NULL_UNION),
85 allowUndefinedUnion: has(OPTION_ALLOW_UNDEFINED_UNION),
86 allowString: has(OPTION_ALLOW_STRING),
87 allowEnum: has(OPTION_ALLOW_ENUM),
88 allowNumber: has(OPTION_ALLOW_NUMBER),
89 allowMix: has(OPTION_ALLOW_MIX),
90 allowBooleanOrUndefined: has(OPTION_ALLOW_BOOLEAN_OR_UNDEFINED),
91 ignoreRhs: has(OPTION_IGNORE_RHS),
94 return ruleArguments.indexOf(name) !== -1;
97 function walk(ctx, checker) {
98 var sourceFile = ctx.sourceFile, options = ctx.options;
99 ts.forEachChild(sourceFile, function cb(node) {
101 case ts.SyntaxKind.BinaryExpression: {
103 if (binaryBooleanExpressionKind(b) !== undefined) {
104 var left = b.left, right = b.right;
105 // If ignore-rhs is off, we don't have to analyze a boolean binary expression
106 // on the left side because it will be checked well enough on its own. However,
107 // if ignore-rhs is on, we have to analyze the overall result of the left
108 // side no matter what, because its right side might not follow the rules.
109 if (!isBooleanBinaryExpression(left)) {
110 checkExpression(left, b);
112 // If ignore-rhs is on, we don't have to analyze the right hand side
113 // We also don't have to analyze the right hand side if it is also a
114 // boolean binary expression; its own inner check is sufficient.
115 if (!(options.ignoreRhs || isBooleanBinaryExpression(right))) {
116 checkExpression(right, b);
121 case ts.SyntaxKind.PrefixUnaryExpression: {
122 var _a = node, operator = _a.operator, operand = _a.operand;
123 if (operator === ts.SyntaxKind.ExclamationToken) {
124 checkExpression(operand, node);
128 case ts.SyntaxKind.IfStatement:
129 case ts.SyntaxKind.WhileStatement:
130 case ts.SyntaxKind.DoStatement: {
132 // If it's a boolean binary expression, we'll check it when recursing.
133 if (!isBooleanBinaryExpression(c.expression)) {
134 checkExpression(c.expression, c);
138 case ts.SyntaxKind.ConditionalExpression:
139 checkExpression(node.condition, node);
141 case ts.SyntaxKind.ForStatement: {
142 var condition = node.condition;
143 if (condition !== undefined) {
144 checkExpression(condition, node);
148 return ts.forEachChild(node, cb);
150 function checkExpression(node, location) {
151 var type = checker.getTypeAtLocation(node);
152 var failure = getTypeFailure(type, options);
153 if (failure !== undefined) {
154 if (failure === 0 /* AlwaysTruthy */ &&
155 !options.strictNullChecks &&
156 (options.allowNullUnion || options.allowUndefinedUnion)) {
157 // OK; It might be null/undefined.
160 ctx.addFailureAtNode(node, showFailure(location, failure, isUnionType(type), options));
164 function getTypeFailure(type, options) {
165 if (isUnionType(type)) {
166 return handleUnion(type, options);
168 var kind = getKind(type);
169 var failure = failureForKind(kind, /*isInUnion*/ false, options);
170 if (failure !== undefined) {
173 switch (triState(kind)) {
175 // Allow 'any'. Allow 'true' itself, but not any other always-truthy type.
176 return tsutils_1.isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.BooleanLiteral)
178 : 0 /* AlwaysTruthy */;
180 // Allow 'false' itself, but not any other always-falsy type
181 return tsutils_1.isTypeFlagSet(type, ts.TypeFlags.BooleanLiteral)
183 : 1 /* AlwaysFalsy */;
188 function isBooleanUndefined(type) {
189 var isTruthy = false;
190 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
192 if (tsutils_1.isTypeFlagSet(ty, ts.TypeFlags.Boolean)) {
195 else if (tsutils_1.isTypeFlagSet(ty, ts.TypeFlags.BooleanLiteral)) {
196 isTruthy = isTruthy || ty.intrinsicName === "true";
197 // tslint:disable-next-line:no-bitwise
199 else if (!tsutils_1.isTypeFlagSet(ty, ts.TypeFlags.Void | ts.TypeFlags.Undefined)) {
205 function handleUnion(type, options) {
206 if (options.allowBooleanOrUndefined) {
207 switch (isBooleanUndefined(type)) {
211 return 1 /* AlwaysFalsy */;
214 // Tracks whether it's possibly truthy.
215 var anyTruthy = false;
216 // Counts falsy kinds to see if there's a mix. Also tracks whether it's possibly falsy.
218 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
220 var kind = getKind(ty);
221 var failure = failureForKind(kind, /*isInUnion*/ true, options);
222 if (failure !== undefined) {
225 switch (triState(kind)) {
237 return seenFalsy === 0
238 ? 0 /* AlwaysTruthy */
240 ? 1 /* AlwaysFalsy */
241 : !options.allowMix && seenFalsy > 1
245 /** Fails if a kind of falsiness is not allowed. */
246 function failureForKind(kind, isInUnion, options) {
249 case 1 /* FalseStringLiteral */:
250 return options.allowString ? undefined : 2 /* String */;
252 case 3 /* FalseNumberLiteral */:
253 return options.allowNumber ? undefined : 3 /* Number */;
255 return options.allowEnum ? undefined : 6 /* Enum */;
257 return isInUnion && !options.allowNullUnion ? 4 /* Null */ : undefined;
258 case 7 /* Undefined */:
259 return isInUnion && !options.allowUndefinedUnion ? 5 /* Undefined */ : undefined;
264 /** Divides a type into always true, always false, or unknown. */
265 function triState(kind) {
269 case 4 /* Boolean */:
273 case 7 /* Undefined */:
274 case 3 /* FalseNumberLiteral */:
275 case 1 /* FalseStringLiteral */:
276 case 5 /* FalseBooleanLiteral */:
278 case 9 /* AlwaysTruthy */:
282 function getKind(type) {
283 return is(ts.TypeFlags.String)
285 : is(ts.TypeFlags.Number)
287 : is(ts.TypeFlags.Boolean)
289 : is(ts.TypeFlags.Null)
291 : is(ts.TypeFlags.Undefined | ts.TypeFlags.Void)
293 : is(ts.TypeFlags.EnumLike)
295 : is(ts.TypeFlags.NumberLiteral)
296 ? numberLiteralIsZero(type)
297 ? 3 /* FalseNumberLiteral */
298 : 9 /* AlwaysTruthy */
299 : is(ts.TypeFlags.StringLiteral)
300 ? stringLiteralIsEmpty(type)
301 ? 1 /* FalseStringLiteral */
302 : 9 /* AlwaysTruthy */
303 : is(ts.TypeFlags.BooleanLiteral)
304 ? type.intrinsicName === "true"
305 ? 9 /* AlwaysTruthy */
306 : 5 /* FalseBooleanLiteral */
307 : 9 /* AlwaysTruthy */;
309 return tsutils_1.isTypeFlagSet(type, flags);
312 function numberLiteralIsZero(type) {
313 // for compatibility with typescript@<2.4.0
314 return type.value !== undefined ? type.value === 0 : type.text === "0";
316 function stringLiteralIsEmpty(type) {
317 // for compatibility with typescript@<2.4.0
318 return (type.value !== undefined ? type.value : type.text) === "";
320 /** Matches `&&` and `||` operators. */
321 function isBooleanBinaryExpression(node) {
322 return (node.kind === ts.SyntaxKind.BinaryExpression &&
323 binaryBooleanExpressionKind(node) !== undefined);
325 function binaryBooleanExpressionKind(node) {
326 switch (node.operatorToken.kind) {
327 case ts.SyntaxKind.AmpersandAmpersandToken:
329 case ts.SyntaxKind.BarBarToken:
335 function stringOr(parts) {
336 switch (parts.length) {
340 return parts[0] + " or " + parts[1];
343 for (var i = 0; i < parts.length - 1; i++) {
344 res += parts[i] + ", ";
346 return res + "or " + parts[parts.length - 1];
349 function isUnionType(type) {
350 return tsutils_1.isTypeFlagSet(type, ts.TypeFlags.Union) && !tsutils_1.isTypeFlagSet(type, ts.TypeFlags.Enum);
352 function showLocation(n) {
354 case ts.SyntaxKind.PrefixUnaryExpression:
355 return "operand for the '!' operator";
356 case ts.SyntaxKind.ConditionalExpression:
358 case ts.SyntaxKind.ForStatement:
359 return "'for' condition";
360 case ts.SyntaxKind.IfStatement:
361 return "'if' condition";
362 case ts.SyntaxKind.WhileStatement:
363 return "'while' condition";
364 case ts.SyntaxKind.DoStatement:
365 return "'do-while' condition";
366 case ts.SyntaxKind.BinaryExpression:
367 return "operand for the '" + binaryBooleanExpressionKind(n) + "' operator";
370 function showFailure(location, ty, unionType, options) {
371 var expectedTypes = showExpectedTypes(options);
372 var expected = expectedTypes.length === 1
373 ? "Only " + expectedTypes[0] + "s are allowed"
374 : "Allowed types are " + stringOr(expectedTypes);
375 var tyFail = showTypeFailure(ty, unionType, options.strictNullChecks);
376 return "This type is not allowed in the " + showLocation(location) + " because it " + tyFail + ". " + expected + ".";
378 function showExpectedTypes(options) {
379 var parts = ["boolean"];
380 if (options.allowNullUnion) {
381 parts.push("null-union");
383 if (options.allowUndefinedUnion) {
384 parts.push("undefined-union");
386 if (options.allowString) {
387 parts.push("string");
389 if (options.allowEnum) {
392 if (options.allowNumber) {
393 parts.push("number");
395 if (options.allowBooleanOrUndefined) {
396 parts.push("boolean-or-undefined");
400 function showTypeFailure(ty, unionType, strictNullChecks) {
401 var is = unionType ? "could be" : "is";
403 case 0 /* AlwaysTruthy */:
404 return strictNullChecks
406 : "is always truthy. It may be null/undefined, but neither " +
407 ("'" + OPTION_ALLOW_NULL_UNION + "' nor '" + OPTION_ALLOW_UNDEFINED_UNION + "' is set");
408 case 1 /* AlwaysFalsy */:
409 return "is always falsy";
411 return is + " a string";
413 return is + " a number";
416 case 5 /* Undefined */:
417 return is + " undefined";
419 return is + " an enum";
421 return "unions more than one truthy/falsy type";
424 var templateObject_1, templateObject_2;