no-constant-binary-expression.js
20 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/**
* @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit
* @author Jordan Eldredge <https://jordaneldredge.com>
*/
"use strict";
const globals = require("globals");
const { isNullLiteral, isConstant, isReferenceToGlobalVariable, isLogicalAssignmentOperator } = require("./utils/ast-utils");
const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set(["+", "-", "*", "/", "%", "|", "^", "&", "**", "<<", ">>", ">>>"]);
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Test if an AST node has a statically knowable constant nullishness. Meaning,
* it will always resolve to a constant value of either: `null`, `undefined`
* or not `null` _or_ `undefined`. An expression that can vary between those
* three states at runtime would return `false`.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The AST node being tested.
* @returns {boolean} Does `node` have constant nullishness?
*/
function hasConstantNullishness(scope, node) {
switch (node.type) {
case "ObjectExpression": // Objects are never nullish
case "ArrayExpression": // Arrays are never nullish
case "ArrowFunctionExpression": // Functions never nullish
case "FunctionExpression": // Functions are never nullish
case "ClassExpression": // Classes are never nullish
case "NewExpression": // Objects are never nullish
case "Literal": // Nullish, or non-nullish, literals never change
case "TemplateLiteral": // A string is never nullish
case "UpdateExpression": // Numbers are never nullish
case "BinaryExpression": // Numbers, strings, or booleans are never nullish
return true;
case "CallExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
const functionName = node.callee.name;
return (functionName === "Boolean" || functionName === "String" || functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee);
}
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantNullishness(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...) /
*/
if (isLogicalAssignmentOperator(node.operator)) {
return false;
}
/*
* The remaining assignment expressions all result in a numeric or
* string (non-nullish) value:
* "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
*/
return true;
case "UnaryExpression":
/*
* "void" Always returns `undefined`
* "typeof" All types are strings, and thus non-nullish
* "!" Boolean is never nullish
* "delete" Returns a boolean, which is never nullish
* Math operators always return numbers or strings, neither of which
* are non-nullish "+", "-", "~"
*/
return true;
case "SequenceExpression": {
const last = node.expressions[node.expressions.length - 1];
return hasConstantNullishness(scope, last);
}
case "Identifier":
return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node is a boolean value that never changes. Specifically we
* test for:
* 1. Literal booleans (`true` or `false`)
* 2. Unary `!` expressions with a constant value
* 3. Constant booleans created via the `Boolean` global function
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Is `node` guaranteed to be a boolean?
*/
function isStaticBoolean(scope, node) {
switch (node.type) {
case "Literal":
return typeof node.value === "boolean";
case "CallExpression":
return node.callee.type === "Identifier" && node.callee.name === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee) &&
(node.arguments.length === 0 || isConstant(scope, node.arguments[0], true));
case "UnaryExpression":
return node.operator === "!" && isConstant(scope, node.argument, true);
default:
return false;
}
}
/**
* Test if an AST node will always give the same result when compared to a
* boolean value. Note that comparison to boolean values is different than
* truthiness.
* https://262.ecma-international.org/5.1/#sec-11.9.3
*
* Javascript `==` operator works by converting the boolean to `1` (true) or
* `+0` (false) and then checks the values `==` equality to that number.
* @param {Scope} scope The scope in which node was found.
* @param {ASTNode} node The node to test.
* @returns {boolean} Will `node` always coerce to the same boolean value?
*/
function hasConstantLooseBooleanComparison(scope, node) {
switch (node.type) {
case "ObjectExpression":
case "ClassExpression":
/**
* In theory objects like:
*
* `{toString: () => a}`
* `{valueOf: () => a}`
*
* Or a classes like:
*
* `class { static toString() { return a } }`
* `class { static valueOf() { return a } }`
*
* Are not constant verifiably when `inBooleanPosition` is
* false, but it's an edge case we've opted not to handle.
*/
return true;
case "ArrayExpression": {
const nonSpreadElements = node.elements.filter(e =>
// Elements can be `null` in sparse arrays: `[,,]`;
e !== null && e.type !== "SpreadElement");
/*
* Possible future direction if needed: We could check if the
* single value would result in variable boolean comparison.
* For now we will err on the side of caution since `[x]` could
* evaluate to `[0]` or `[1]`.
*/
return node.elements.length === 0 || nonSpreadElements.length > 1;
}
case "ArrowFunctionExpression":
case "FunctionExpression":
return true;
case "UnaryExpression":
if (node.operator === "void" || // Always returns `undefined`
node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1.
) {
return true;
}
if (node.operator === "!") {
return isConstant(scope, node.argument, true);
}
/*
* We won't try to reason about +, -, ~, or delete
* In theory, for the mathematical operators, we could look at the
* argument and try to determine if it coerces to a constant numeric
* value.
*/
return false;
case "NewExpression": // Objects might have custom `.valueOf` or `.toString`.
return false;
case "CallExpression": {
if (node.callee.type === "Identifier" &&
node.callee.name === "Boolean" &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return node.arguments.length === 0 || isConstant(scope, node.arguments[0], true);
}
return false;
}
case "Literal": // True or false, literals never change
return true;
case "Identifier":
return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
case "TemplateLiteral":
/*
* In theory we could try to check if the quasi are sufficient to
* prove that the expression will always be true, but it would be
* tricky to get right. For example: `000.${foo}000`
*/
return node.expressions.length === 0;
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantLooseBooleanComparison(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...)
*
* The remaining assignment expressions all result in a numeric or
* string (non-nullish) values which could be truthy or falsy:
* "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
*/
return false;
case "SequenceExpression": {
const last = node.expressions[node.expressions.length - 1];
return hasConstantLooseBooleanComparison(scope, last);
}
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node will always give the same result when _strictly_ compared
* to a boolean value. This can happen if the expression can never be boolean, or
* if it is always the same boolean value.
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Will `node` always give the same result when compared to a
* static boolean value?
*/
function hasConstantStrictBooleanComparison(scope, node) {
switch (node.type) {
case "ObjectExpression": // Objects are not booleans
case "ArrayExpression": // Arrays are not booleans
case "ArrowFunctionExpression": // Functions are not booleans
case "FunctionExpression":
case "ClassExpression": // Classes are not booleans
case "NewExpression": // Objects are not booleans
case "TemplateLiteral": // Strings are not booleans
case "Literal": // True, false, or not boolean, literals never change.
case "UpdateExpression": // Numbers are not booleans
return true;
case "BinaryExpression":
return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator);
case "UnaryExpression": {
if (node.operator === "delete") {
return false;
}
if (node.operator === "!") {
return isConstant(scope, node.argument, true);
}
/*
* The remaining operators return either strings or numbers, neither
* of which are boolean.
*/
return true;
}
case "SequenceExpression": {
const last = node.expressions[node.expressions.length - 1];
return hasConstantStrictBooleanComparison(scope, last);
}
case "Identifier":
return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
case "AssignmentExpression":
if (node.operator === "=") {
return hasConstantStrictBooleanComparison(scope, node.right);
}
/*
* Handling short-circuiting assignment operators would require
* walking the scope. We won't attempt that (for now...)
*/
if (isLogicalAssignmentOperator(node.operator)) {
return false;
}
/*
* The remaining assignment expressions all result in either a number
* or a string, neither of which can ever be boolean.
*/
return true;
case "CallExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
const functionName = node.callee.name;
if (
(functionName === "String" || functionName === "Number") &&
isReferenceToGlobalVariable(scope, node.callee)
) {
return true;
}
if (functionName === "Boolean" && isReferenceToGlobalVariable(scope, node.callee)) {
return (
node.arguments.length === 0 || isConstant(scope, node.arguments[0], true));
}
return false;
}
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Test if an AST node will always result in a newly constructed object
* @param {Scope} scope The scope in which the node was found.
* @param {ASTNode} node The node to test
* @returns {boolean} Will `node` always be new?
*/
function isAlwaysNew(scope, node) {
switch (node.type) {
case "ObjectExpression":
case "ArrayExpression":
case "ArrowFunctionExpression":
case "FunctionExpression":
case "ClassExpression":
return true;
case "NewExpression": {
if (node.callee.type !== "Identifier") {
return false;
}
/*
* All the built-in constructors are always new, but
* user-defined constructors could return a sentinel
* object.
*
* Catching these is especially useful for primitive constructures
* which return boxed values, a surprising gotcha' in JavaScript.
*/
return Object.hasOwnProperty.call(globals.builtin, node.callee.name) &&
isReferenceToGlobalVariable(scope, node.callee);
}
case "Literal":
// Regular expressions are objects, and thus always new
return typeof node.regex === "object";
case "SequenceExpression": {
const last = node.expressions[node.expressions.length - 1];
return isAlwaysNew(scope, last);
}
case "AssignmentExpression":
if (node.operator === "=") {
return isAlwaysNew(scope, node.right);
}
return false;
case "ConditionalExpression":
return isAlwaysNew(scope, node.consequent) && isAlwaysNew(scope, node.alternate);
case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
case "JSXFragment":
return false;
default:
return false;
}
}
/**
* Checks whether or not a node is `null` or `undefined`. Similar to the one
* found in ast-utils.js, but this one correctly handles the edge case that
* `undefined` has been redefined.
* @param {Scope} scope Scope in which the expression was found.
* @param {ASTNode} node A node to check.
* @returns {boolean} Whether or not the node is a `null` or `undefined`.
* @public
*/
function isNullOrUndefined(scope, node) {
return (
isNullLiteral(node) ||
(node.type === "Identifier" && node.name === "undefined" && isReferenceToGlobalVariable(scope, node)) ||
(node.type === "UnaryExpression" && node.operator === "void")
);
}
/**
* Checks if one operand will cause the result to be constant.
* @param {Scope} scope Scope in which the expression was found.
* @param {ASTNode} a One side of the expression
* @param {ASTNode} b The other side of the expression
* @param {string} operator The binary expression operator
* @returns {ASTNode | null} The node which will cause the expression to have a constant result.
*/
function findBinaryExpressionConstantOperand(scope, a, b, operator) {
if (operator === "==" || operator === "!=") {
if (
(isNullOrUndefined(scope, a) && hasConstantNullishness(scope, b)) ||
(isStaticBoolean(scope, a) && hasConstantLooseBooleanComparison(scope, b))
) {
return b;
}
} else if (operator === "===" || operator === "!==") {
if (
(isNullOrUndefined(scope, a) && hasConstantNullishness(scope, b)) ||
(isStaticBoolean(scope, a) && hasConstantStrictBooleanComparison(scope, b))
) {
return b;
}
}
return null;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow expressions where the operation doesn't affect the value",
recommended: false,
url: "https://eslint.org/docs/rules/no-constant-binary-expression"
},
schema: [],
messages: {
constantBinaryOperand: "Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.",
constantShortCircuit: "Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.",
alwaysNew: "Unexpected comparison to newly constructed object. These two values can never be equal.",
bothAlwaysNew: "Unexpected comparison of two newly constructed objects. These two values can never be equal."
}
},
create(context) {
return {
LogicalExpression(node) {
const { operator, left } = node;
const scope = context.getScope();
if ((operator === "&&" || operator === "||") && isConstant(scope, left, true)) {
context.report({ node: left, messageId: "constantShortCircuit", data: { property: "truthiness", operator } });
} else if (operator === "??" && hasConstantNullishness(scope, left)) {
context.report({ node: left, messageId: "constantShortCircuit", data: { property: "nullishness", operator } });
}
},
BinaryExpression(node) {
const scope = context.getScope();
const { right, left, operator } = node;
const rightConstantOperand = findBinaryExpressionConstantOperand(scope, left, right, operator);
const leftConstantOperand = findBinaryExpressionConstantOperand(scope, right, left, operator);
if (rightConstantOperand) {
context.report({ node: rightConstantOperand, messageId: "constantBinaryOperand", data: { operator, otherSide: "left" } });
} else if (leftConstantOperand) {
context.report({ node: leftConstantOperand, messageId: "constantBinaryOperand", data: { operator, otherSide: "right" } });
} else if (operator === "===" || operator === "!==") {
if (isAlwaysNew(scope, left)) {
context.report({ node: left, messageId: "alwaysNew" });
} else if (isAlwaysNew(scope, right)) {
context.report({ node: right, messageId: "alwaysNew" });
}
} else if (operator === "==" || operator === "!=") {
/*
* If both sides are "new", then both sides are objects and
* therefore they will be compared by reference even with `==`
* equality.
*/
if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) {
context.report({ node: left, messageId: "bothAlwaysNew" });
}
}
}
/*
* In theory we could handle short-circuiting assignment operators,
* for some constant values, but that would require walking the
* scope to find the value of the variable being assigned. This is
* dependant on https://github.com/eslint/eslint/issues/13776
*
* AssignmentExpression() {},
*/
};
}
};