|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2019 Palantir Technologies, Inc. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +import { isBinaryExpression, isTypeFlagSet, isUnionType } from "tsutils"; |
| 19 | +import * as ts from "typescript"; |
| 20 | + |
| 21 | +import * as Lint from "../index"; |
| 22 | + |
| 23 | +import { codeExamples } from "./code-examples/strictComparisons.examples"; |
| 24 | + |
| 25 | +const OPTION_ALLOW_OBJECT_EQUAL_COMPARISON = "allow-object-equal-comparison"; |
| 26 | +const OPTION_ALLOW_STRING_ORDER_COMPARISON = "allow-string-order-comparison"; |
| 27 | + |
| 28 | +const enum TypeKind { |
| 29 | + Any = 0, |
| 30 | + Number = 1, |
| 31 | + Enum = 2, |
| 32 | + String = 3, |
| 33 | + Boolean = 4, |
| 34 | + Null = 5, |
| 35 | + Undefined = 6, |
| 36 | + Object = 7, |
| 37 | +} |
| 38 | + |
| 39 | +const typeNames = { |
| 40 | + [TypeKind.Any]: "any", |
| 41 | + [TypeKind.Number]: "number", |
| 42 | + [TypeKind.Enum]: "enum", |
| 43 | + [TypeKind.String]: "string", |
| 44 | + [TypeKind.Boolean]: "boolean", |
| 45 | + [TypeKind.Null]: "null", |
| 46 | + [TypeKind.Undefined]: "undefined", |
| 47 | + [TypeKind.Object]: "object", |
| 48 | +}; |
| 49 | + |
| 50 | +interface Options { |
| 51 | + [OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]?: boolean; |
| 52 | + [OPTION_ALLOW_STRING_ORDER_COMPARISON]?: boolean; |
| 53 | +} |
| 54 | + |
| 55 | +export class Rule extends Lint.Rules.TypedRule { |
| 56 | + /* tslint:disable:object-literal-sort-keys */ |
| 57 | + public static metadata: Lint.IRuleMetadata = { |
| 58 | + ruleName: "strict-comparisons", |
| 59 | + description: "Only allow comparisons between primitives.", |
| 60 | + optionsDescription: Lint.Utils.dedent` |
| 61 | + One of the following arguments may be optionally provided: |
| 62 | + * \`${OPTION_ALLOW_OBJECT_EQUAL_COMPARISON}\` allows \`!=\` \`==\` \`!==\` \`===\` comparison between any types. |
| 63 | + * \`${OPTION_ALLOW_STRING_ORDER_COMPARISON}\` allows \`>\` \`<\` \`>=\` \`<=\` comparison between strings.`, |
| 64 | + options: { |
| 65 | + type: "object", |
| 66 | + properties: { |
| 67 | + [OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]: { |
| 68 | + type: "boolean", |
| 69 | + }, |
| 70 | + [OPTION_ALLOW_STRING_ORDER_COMPARISON]: { |
| 71 | + type: "boolean", |
| 72 | + }, |
| 73 | + }, |
| 74 | + }, |
| 75 | + optionExamples: [ |
| 76 | + true, |
| 77 | + [ |
| 78 | + true, |
| 79 | + { |
| 80 | + [OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]: false, |
| 81 | + [OPTION_ALLOW_STRING_ORDER_COMPARISON]: false, |
| 82 | + }, |
| 83 | + ], |
| 84 | + ], |
| 85 | + rationale: Lint.Utils.dedent` |
| 86 | + When using comparison operators to compare objects, they compare references and not values. |
| 87 | + This is often done accidentally. |
| 88 | + With this rule, \`>\`, \`>=\`, \`<\`, \`<=\` operators are only allowed when comparing \`numbers\`. |
| 89 | + \`===\`, \`!==\` are allowed for \`number\` \`string\` and \`boolean\` types and if one of the |
| 90 | + operands is \`null\` or \`undefined\`. |
| 91 | + `, |
| 92 | + type: "functionality", |
| 93 | + typescriptOnly: false, |
| 94 | + requiresTypeInfo: true, |
| 95 | + codeExamples, |
| 96 | + }; |
| 97 | + /* tslint:enable:object-literal-sort-keys */ |
| 98 | + |
| 99 | + public static INVALID_TYPES(types1: TypeKind[], types2: TypeKind[]) { |
| 100 | + const types1String = types1.map(type => typeNames[type]).join(" | "); |
| 101 | + const types2String = types2.map(type => typeNames[type]).join(" | "); |
| 102 | + |
| 103 | + return `Cannot compare type '${types1String}' to type '${types2String}'.`; |
| 104 | + } |
| 105 | + |
| 106 | + public static INVALID_TYPE_FOR_OPERATOR(type: TypeKind, comparator: string) { |
| 107 | + return `Cannot use '${comparator}' comparator for type '${typeNames[type]}'.`; |
| 108 | + } |
| 109 | + |
| 110 | + public applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] { |
| 111 | + return this.applyWithFunction(sourceFile, walk, this.getRuleOptions(), program); |
| 112 | + } |
| 113 | + |
| 114 | + private getRuleOptions(): Options { |
| 115 | + if (this.ruleArguments[0] === undefined) { |
| 116 | + return {}; |
| 117 | + } else { |
| 118 | + return this.ruleArguments[0] as Options; |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +function walk(ctx: Lint.WalkContext<Options>, program: ts.Program) { |
| 124 | + const { sourceFile, options } = ctx; |
| 125 | + |
| 126 | + const checker = program.getTypeChecker(); |
| 127 | + |
| 128 | + return ts.forEachChild(sourceFile, function cb(node: ts.Node): void { |
| 129 | + if (isBinaryExpression(node) && isComparisonOperator(node)) { |
| 130 | + const leftType = checker.getTypeAtLocation(node.left); |
| 131 | + const rightType = checker.getTypeAtLocation(node.right); |
| 132 | + |
| 133 | + const leftKinds: TypeKind[] = getTypes(leftType); |
| 134 | + const rightKinds: TypeKind[] = getTypes(rightType); |
| 135 | + |
| 136 | + const operandKind = getStrictestComparableType(leftKinds, rightKinds); |
| 137 | + |
| 138 | + if (operandKind === undefined) { |
| 139 | + const failureString = Rule.INVALID_TYPES(leftKinds, rightKinds); |
| 140 | + ctx.addFailureAtNode(node, failureString); |
| 141 | + } else { |
| 142 | + const failureString = Rule.INVALID_TYPE_FOR_OPERATOR( |
| 143 | + operandKind, |
| 144 | + node.operatorToken.getText(), |
| 145 | + ); |
| 146 | + const isEquality = isEqualityOperator(node); |
| 147 | + if (isEquality) { |
| 148 | + // Check !=, ==, !==, === |
| 149 | + switch (operandKind) { |
| 150 | + case TypeKind.Any: |
| 151 | + case TypeKind.Number: |
| 152 | + case TypeKind.Enum: |
| 153 | + case TypeKind.String: |
| 154 | + case TypeKind.Boolean: |
| 155 | + break; |
| 156 | + case TypeKind.Null: |
| 157 | + case TypeKind.Undefined: |
| 158 | + case TypeKind.Object: |
| 159 | + if (options[OPTION_ALLOW_OBJECT_EQUAL_COMPARISON]) { |
| 160 | + break; |
| 161 | + } |
| 162 | + ctx.addFailureAtNode(node, failureString); |
| 163 | + break; |
| 164 | + default: |
| 165 | + ctx.addFailureAtNode(node, failureString); |
| 166 | + } |
| 167 | + } else { |
| 168 | + // Check >, <, >=, <= |
| 169 | + switch (operandKind) { |
| 170 | + case TypeKind.Any: |
| 171 | + case TypeKind.Number: |
| 172 | + break; |
| 173 | + case TypeKind.String: |
| 174 | + if (options[OPTION_ALLOW_STRING_ORDER_COMPARISON]) { |
| 175 | + break; |
| 176 | + } |
| 177 | + ctx.addFailureAtNode(node, failureString); |
| 178 | + break; |
| 179 | + default: |
| 180 | + ctx.addFailureAtNode(node, failureString); |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + } |
| 185 | + return ts.forEachChild(node, cb); |
| 186 | + }); |
| 187 | +} |
| 188 | + |
| 189 | +function getTypes(types: ts.Type): TypeKind[] { |
| 190 | + // Compatibility for TypeScript pre-2.4, which used EnumLiteralType instead of LiteralType |
| 191 | + const baseType = ((types as any) as { baseType: ts.LiteralType }).baseType; |
| 192 | + return isUnionType(types) |
| 193 | + ? Array.from(new Set(types.types.map(getKind))) |
| 194 | + : isTypeFlagSet(types, ts.TypeFlags.EnumLiteral) && typeof baseType !== "undefined" |
| 195 | + ? [getKind(baseType)] |
| 196 | + : [getKind(types)]; |
| 197 | +} |
| 198 | + |
| 199 | +function getStrictestComparableType( |
| 200 | + typesLeft: TypeKind[], |
| 201 | + typesRight: TypeKind[], |
| 202 | +): TypeKind | undefined { |
| 203 | + const overlappingTypes = typesLeft.filter(type => typesRight.indexOf(type) >= 0); |
| 204 | + |
| 205 | + if (overlappingTypes.length > 0) { |
| 206 | + return getStrictestKind(overlappingTypes); |
| 207 | + } else { |
| 208 | + // In case one of the types is "any", get the strictest type of the other array |
| 209 | + if (arrayContainsKind(typesLeft, [TypeKind.Any])) { |
| 210 | + return getStrictestKind(typesRight); |
| 211 | + } |
| 212 | + if (arrayContainsKind(typesRight, [TypeKind.Any])) { |
| 213 | + return getStrictestKind(typesLeft); |
| 214 | + } |
| 215 | + |
| 216 | + // In case one array contains NullOrUndefined and the other an Object, return Object |
| 217 | + if ( |
| 218 | + (arrayContainsKind(typesLeft, [TypeKind.Null, TypeKind.Undefined]) && |
| 219 | + arrayContainsKind(typesRight, [TypeKind.Object])) || |
| 220 | + (arrayContainsKind(typesRight, [TypeKind.Null, TypeKind.Undefined]) && |
| 221 | + arrayContainsKind(typesLeft, [TypeKind.Object])) |
| 222 | + ) { |
| 223 | + return TypeKind.Object; |
| 224 | + } |
| 225 | + return undefined; |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +function arrayContainsKind(types: TypeKind[], typeToCheck: TypeKind[]): boolean { |
| 230 | + return types.some(type => typeToCheck.indexOf(type) >= 0); |
| 231 | +} |
| 232 | + |
| 233 | +function getStrictestKind(types: TypeKind[]): TypeKind { |
| 234 | + // tslint:disable-next-line:no-unsafe-any |
| 235 | + return Math.max.apply(Math, types); |
| 236 | +} |
| 237 | + |
| 238 | +function isComparisonOperator(node: ts.BinaryExpression): boolean { |
| 239 | + switch (node.operatorToken.kind) { |
| 240 | + case ts.SyntaxKind.LessThanToken: |
| 241 | + case ts.SyntaxKind.GreaterThanToken: |
| 242 | + case ts.SyntaxKind.LessThanEqualsToken: |
| 243 | + case ts.SyntaxKind.GreaterThanEqualsToken: |
| 244 | + case ts.SyntaxKind.EqualsEqualsToken: |
| 245 | + case ts.SyntaxKind.ExclamationEqualsToken: |
| 246 | + case ts.SyntaxKind.EqualsEqualsEqualsToken: |
| 247 | + case ts.SyntaxKind.ExclamationEqualsEqualsToken: |
| 248 | + return true; |
| 249 | + default: |
| 250 | + return false; |
| 251 | + } |
| 252 | +} |
| 253 | + |
| 254 | +function isEqualityOperator(node: ts.BinaryExpression): boolean { |
| 255 | + switch (node.operatorToken.kind) { |
| 256 | + case ts.SyntaxKind.EqualsEqualsToken: |
| 257 | + case ts.SyntaxKind.ExclamationEqualsToken: |
| 258 | + case ts.SyntaxKind.EqualsEqualsEqualsToken: |
| 259 | + case ts.SyntaxKind.ExclamationEqualsEqualsToken: |
| 260 | + return true; |
| 261 | + default: |
| 262 | + return false; |
| 263 | + } |
| 264 | +} |
| 265 | + |
| 266 | +function getKind(type: ts.Type): TypeKind { |
| 267 | + // tslint:disable:no-bitwise |
| 268 | + if (is(ts.TypeFlags.String | ts.TypeFlags.StringLiteral)) { |
| 269 | + return TypeKind.String; |
| 270 | + } else if (is(ts.TypeFlags.Number | ts.TypeFlags.NumberLiteral)) { |
| 271 | + return TypeKind.Number; |
| 272 | + } else if (is(ts.TypeFlags.BooleanLike)) { |
| 273 | + return TypeKind.Boolean; |
| 274 | + } else if (is(ts.TypeFlags.Null)) { |
| 275 | + return TypeKind.Null; |
| 276 | + } else if (is(ts.TypeFlags.Undefined)) { |
| 277 | + return TypeKind.Undefined; |
| 278 | + } else if (is(ts.TypeFlags.Any)) { |
| 279 | + return TypeKind.Any; |
| 280 | + } else { |
| 281 | + return TypeKind.Object; |
| 282 | + } |
| 283 | + // tslint:enable:no-bitwise |
| 284 | + |
| 285 | + function is(flags: ts.TypeFlags) { |
| 286 | + return isTypeFlagSet(type, flags); |
| 287 | + } |
| 288 | +} |
0 commit comments