Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Add no-boolean-literal-compare rule #2013

Merged
merged 2 commits into from
Jan 11, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 42 additions & 8 deletions docs/_data/rules.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,22 +139,44 @@
"ruleName": "comment-format",
"description": "Enforces formatting rules for single-line comments.",
"rationale": "Helps maintain a consistent, readable style in your codebase.",
"optionsDescription": "\nThree arguments may be optionally provided:\n\n* `\"check-space\"` requires that all single-line comments must begin with a space, as in `// comment`\n * note that comments starting with `///` are also allowed, for things such as `///<reference>`\n* `\"check-lowercase\"` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n* `\"check-uppercase\"` requires that the first non-whitespace character of a comment must be uppercase, if applicable.",
"optionsDescription": "\nThree arguments may be optionally provided:\n\n* `\"check-space\"` requires that all single-line comments must begin with a space, as in `// comment`\n * note that comments starting with `///` are also allowed, for things such as `///<reference>`\n* `\"check-lowercase\"` requires that the first non-whitespace character of a comment must be lowercase, if applicable.\n* `\"check-uppercase\"` requires that the first non-whitespace character of a comment must be uppercase, if applicable.\n\nExceptions to `\"check-lowercase\"` or `\"check-uppercase\"` can be managed with object that may be passed as last argument.\n\nOne of two options can be provided in this object:\n \n * `\"ignoreWords\"` - array of strings - words that will be ignored at the beginning of the comment.\n * `\"ignorePattern\"` - string - RegExp pattern that will be ignored at the beginning of the comment.\n",
"options": {
"type": "array",
"items": {
"type": "string",
"enum": [
"check-space",
"check-lowercase",
"check-uppercase"
"anyOf": [
{
"type": "string",
"enum": [
"check-space",
"check-lowercase",
"check-uppercase"
]
},
{
"type": "object",
"properties": {
"ignoreWords": {
"type": "array",
"items": {
"type": "string"
}
},
"ignorePattern": {
"type": "string"
}
},
"minProperties": 1,
"maxProperties": 1
}
]
},
"minLength": 1,
"maxLength": 3
"maxLength": 4
},
"optionExamples": [
"[true, \"check-space\", \"check-lowercase\"]"
"[true, \"check-space\", \"check-uppercase\"]",
"[true, \"check-lowercase\", {\"ignoreWords\": [\"TODO\", \"HACK\"]}]",
"[true, \"check-lowercase\", {\"ignorePattern\": \"STD\\w{2,3}\\b\"}]"
],
"type": "style",
"typescriptOnly": false
Expand Down Expand Up @@ -559,6 +581,18 @@
"type": "functionality",
"typescriptOnly": false
},
{
"ruleName": "no-boolean-compare",
"description": "Warns on comparison to a boolean literal, as in `x === true`.",
"hasFix": true,
"optionsDescription": "Not configurable.",
"options": null,
"optionExamples": [
"true"
],
"type": "style",
"typescriptOnly": true
},
{
"ruleName": "no-conditional-assignment",
"description": "Disallows any type of assignment in conditionals.",
Expand Down
68 changes: 54 additions & 14 deletions docs/rules/comment-format/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,46 @@
ruleName: comment-format
description: Enforces formatting rules for single-line comments.
rationale: 'Helps maintain a consistent, readable style in your codebase.'
optionsDescription: |-
optionsDescription: |

Three arguments may be optionally provided:

* `"check-space"` requires that all single-line comments must begin with a space, as in `// comment`
* note that comments starting with `///` are also allowed, for things such as `///<reference>`
* `"check-lowercase"` requires that the first non-whitespace character of a comment must be lowercase, if applicable.
* `"check-uppercase"` requires that the first non-whitespace character of a comment must be uppercase, if applicable.

Exceptions to `"check-lowercase"` or `"check-uppercase"` can be managed with object that may be passed as last argument.

One of two options can be provided in this object:

* `"ignoreWords"` - array of strings - words that will be ignored at the beginning of the comment.
* `"ignorePattern"` - string - RegExp pattern that will be ignored at the beginning of the comment.
options:
type: array
items:
type: string
enum:
- check-space
- check-lowercase
- check-uppercase
anyOf:
- type: string
enum:
- check-space
- check-lowercase
- check-uppercase
- type: object
properties:
ignoreWords:
type: array
items:
type: string
ignorePattern:
type: string
minProperties: 1
maxProperties: 1
minLength: 1
maxLength: 3
maxLength: 4
optionExamples:
- '[true, "check-space", "check-lowercase"]'
- '[true, "check-space", "check-uppercase"]'
- '[true, "check-lowercase", {"ignoreWords": ["TODO", "HACK"]}]'
- '[true, "check-lowercase", {"ignorePattern": "STD\w{2,3}\b"}]'
type: style
typescriptOnly: false
layout: rule
Expand All @@ -30,14 +50,34 @@
{
"type": "array",
"items": {
"type": "string",
"enum": [
"check-space",
"check-lowercase",
"check-uppercase"
"anyOf": [
{
"type": "string",
"enum": [
"check-space",
"check-lowercase",
"check-uppercase"
]
},
{
"type": "object",
"properties": {
"ignoreWords": {
"type": "array",
"items": {
"type": "string"
}
},
"ignorePattern": {
"type": "string"
}
},
"minProperties": 1,
"maxProperties": 1
}
]
},
"minLength": 1,
"maxLength": 3
"maxLength": 4
}
---
14 changes: 14 additions & 0 deletions docs/rules/no-boolean-compare/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
ruleName: no-boolean-compare
description: 'Warns on comparison to a boolean literal, as in `x === true`.'
hasFix: true
optionsDescription: Not configurable.
options: null
optionExamples:
- 'true'
type: style
typescriptOnly: true
layout: rule
title: 'Rule: no-boolean-compare'
optionsJSON: 'null'
---
4 changes: 4 additions & 0 deletions src/language/rule/rule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ export class Replacement {
return replacements.reduce((text, r) => r.apply(text), content);
}

public static deleteFromTo(start: number, end: number): Replacement {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you use RuleWalker.deleteText(start: number, length: number) instead?

return new Replacement(start, end - start, "");
}

constructor(private innerStart: number, private innerLength: number, private innerText: string) {
}

Expand Down
114 changes: 114 additions & 0 deletions src/rules/noBooleanCompareRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* @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 * as ts from "typescript";

import * as Lint from "../index";

export class Rule extends Lint.Rules.TypedRule {
/* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "no-boolean-compare",
description: "Warns on comparison to a boolean literal, as in `x === true`.",
hasFix: true,
optionsDescription: "Not configurable.",
options: null,
optionExamples: ["true"],
type: "style",
typescriptOnly: true,
requiresTypeInfo: true,
};
/* tslint:enable:object-literal-sort-keys */

public static FAILURE_STRING(negate: boolean) {
return `This expression is unnecessarily compared to a boolean. Just ${negate ? "negate it" : "use it directly"}.`;
}

public applyWithProgram(sourceFile: ts.SourceFile, langSvc: ts.LanguageService): Lint.RuleFailure[] {
return this.applyWithWalker(new Walker(sourceFile, this.getOptions(), langSvc.getProgram()));
}
}

class Walker extends Lint.ProgramAwareRuleWalker {
public visitBinaryExpression(node: ts.BinaryExpression) {
this.check(node);
super.visitBinaryExpression(node);
}

private check(node: ts.BinaryExpression) {
const comparison = deconstructComparison(node);
if (comparison === undefined) {
return;
}

const { negate, expression } = comparison;
const type = this.getTypeChecker().getTypeAtLocation(expression);
if (!Lint.isTypeFlagSet(type, ts.TypeFlags.Boolean)) {
return;
}

const deleted = node.left === expression
? Lint.Replacement.deleteFromTo(node.left.end, node.end)
: Lint.Replacement.deleteFromTo(node.getStart(), node.right.getStart());
const replacements = [deleted];
if (negate) {
replacements.push(this.appendText(node.getStart(), "!"));
}

this.addFailureAtNode(expression, Rule.FAILURE_STRING(negate), this.createFix(...replacements));
}
}

function deconstructComparison(node: ts.BinaryExpression): { negate: boolean, expression: ts.Expression } | undefined {
const { left, operatorToken, right } = node;
const operator = operatorKind(operatorToken);
if (operator === undefined) {
return undefined;
}

const leftValue = booleanFromExpression(left);
if (leftValue !== undefined) {
return { negate: leftValue !== operator, expression: right };
}
const rightValue = booleanFromExpression(right);
if (rightValue !== undefined) {
return { negate: rightValue !== operator, expression: left };
}
return undefined;
}

function operatorKind(operatorToken: ts.BinaryOperatorToken): boolean | undefined {
switch (operatorToken.kind) {
case ts.SyntaxKind.EqualsEqualsToken: case ts.SyntaxKind.EqualsEqualsEqualsToken:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cases on separate lines

return true;
case ts.SyntaxKind.ExclamationEqualsToken: case ts.SyntaxKind.ExclamationEqualsEqualsToken:
return false;
default:
return undefined;
}
}

function booleanFromExpression(node: ts.Expression): boolean | undefined {
switch (node.kind) {
case ts.SyntaxKind.TrueKeyword:
return true;
case ts.SyntaxKind.FalseKeyword:
return false;
default:
return undefined;
}
}
19 changes: 19 additions & 0 deletions test/rules/no-boolean-compare/test.ts.fix
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
declare const x: boolean;

x;
x;

!x;
!x;

!x;
!x;

x;
x;

x;

declare const y: boolean | undefined;
y === true;

30 changes: 30 additions & 0 deletions test/rules/no-boolean-compare/test.ts.lint
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
declare const x: boolean;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add cases for more complex expressions like functions, result of binary boolean expression, and negating a boolean


x === true;
~ [T]
true === x;
~ [T]

x === false;
~ [F]
false === x;
~ [F]

x !== true;
~ [F]
true !== x;
~ [F]

x !== false;
~ [T]
false !== x;
~ [T]

x == true;
~ [T]

declare const y: boolean | undefined;
y === true;

[T]: This expression is unnecessarily compared to a boolean. Just use it directly.
[F]: This expression is unnecessarily compared to a boolean. Just negate it.
5 changes: 5 additions & 0 deletions test/rules/no-boolean-compare/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"compilerOptions": {
"strictNullChecks": true
}
}
8 changes: 8 additions & 0 deletions test/rules/no-boolean-compare/tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"linterOptions": {
"typeCheck": true
},
"rules": {
"no-boolean-compare": true
}
}