no-constant-binary-expression.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /**
  2. * @fileoverview Rule to flag constant comparisons and logical expressions that always/never short circuit
  3. * @author Jordan Eldredge <https://jordaneldredge.com>
  4. */
  5. "use strict";
  6. const { isNullLiteral, isConstant, isReferenceToGlobalVariable, isLogicalAssignmentOperator, ECMASCRIPT_GLOBALS } = require("./utils/ast-utils");
  7. const NUMERIC_OR_STRING_BINARY_OPERATORS = new Set(["+", "-", "*", "/", "%", "|", "^", "&", "**", "<<", ">>", ">>>"]);
  8. //------------------------------------------------------------------------------
  9. // Helpers
  10. //------------------------------------------------------------------------------
  11. /**
  12. * Checks whether or not a node is `null` or `undefined`. Similar to the one
  13. * found in ast-utils.js, but this one correctly handles the edge case that
  14. * `undefined` has been redefined.
  15. * @param {Scope} scope Scope in which the expression was found.
  16. * @param {ASTNode} node A node to check.
  17. * @returns {boolean} Whether or not the node is a `null` or `undefined`.
  18. * @public
  19. */
  20. function isNullOrUndefined(scope, node) {
  21. return (
  22. isNullLiteral(node) ||
  23. (node.type === "Identifier" && node.name === "undefined" && isReferenceToGlobalVariable(scope, node)) ||
  24. (node.type === "UnaryExpression" && node.operator === "void")
  25. );
  26. }
  27. /**
  28. * Test if an AST node has a statically knowable constant nullishness. Meaning,
  29. * it will always resolve to a constant value of either: `null`, `undefined`
  30. * or not `null` _or_ `undefined`. An expression that can vary between those
  31. * three states at runtime would return `false`.
  32. * @param {Scope} scope The scope in which the node was found.
  33. * @param {ASTNode} node The AST node being tested.
  34. * @param {boolean} nonNullish if `true` then nullish values are not considered constant.
  35. * @returns {boolean} Does `node` have constant nullishness?
  36. */
  37. function hasConstantNullishness(scope, node, nonNullish) {
  38. if (nonNullish && isNullOrUndefined(scope, node)) {
  39. return false;
  40. }
  41. switch (node.type) {
  42. case "ObjectExpression": // Objects are never nullish
  43. case "ArrayExpression": // Arrays are never nullish
  44. case "ArrowFunctionExpression": // Functions never nullish
  45. case "FunctionExpression": // Functions are never nullish
  46. case "ClassExpression": // Classes are never nullish
  47. case "NewExpression": // Objects are never nullish
  48. case "Literal": // Nullish, or non-nullish, literals never change
  49. case "TemplateLiteral": // A string is never nullish
  50. case "UpdateExpression": // Numbers are never nullish
  51. case "BinaryExpression": // Numbers, strings, or booleans are never nullish
  52. return true;
  53. case "CallExpression": {
  54. if (node.callee.type !== "Identifier") {
  55. return false;
  56. }
  57. const functionName = node.callee.name;
  58. return (functionName === "Boolean" || functionName === "String" || functionName === "Number") &&
  59. isReferenceToGlobalVariable(scope, node.callee);
  60. }
  61. case "LogicalExpression": {
  62. return node.operator === "??" && hasConstantNullishness(scope, node.right, true);
  63. }
  64. case "AssignmentExpression":
  65. if (node.operator === "=") {
  66. return hasConstantNullishness(scope, node.right, nonNullish);
  67. }
  68. /*
  69. * Handling short-circuiting assignment operators would require
  70. * walking the scope. We won't attempt that (for now...) /
  71. */
  72. if (isLogicalAssignmentOperator(node.operator)) {
  73. return false;
  74. }
  75. /*
  76. * The remaining assignment expressions all result in a numeric or
  77. * string (non-nullish) value:
  78. * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
  79. */
  80. return true;
  81. case "UnaryExpression":
  82. /*
  83. * "void" Always returns `undefined`
  84. * "typeof" All types are strings, and thus non-nullish
  85. * "!" Boolean is never nullish
  86. * "delete" Returns a boolean, which is never nullish
  87. * Math operators always return numbers or strings, neither of which
  88. * are non-nullish "+", "-", "~"
  89. */
  90. return true;
  91. case "SequenceExpression": {
  92. const last = node.expressions.at(-1);
  93. return hasConstantNullishness(scope, last, nonNullish);
  94. }
  95. case "Identifier":
  96. return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
  97. case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
  98. case "JSXFragment":
  99. return false;
  100. default:
  101. return false;
  102. }
  103. }
  104. /**
  105. * Test if an AST node is a boolean value that never changes. Specifically we
  106. * test for:
  107. * 1. Literal booleans (`true` or `false`)
  108. * 2. Unary `!` expressions with a constant value
  109. * 3. Constant booleans created via the `Boolean` global function
  110. * @param {Scope} scope The scope in which the node was found.
  111. * @param {ASTNode} node The node to test
  112. * @returns {boolean} Is `node` guaranteed to be a boolean?
  113. */
  114. function isStaticBoolean(scope, node) {
  115. switch (node.type) {
  116. case "Literal":
  117. return typeof node.value === "boolean";
  118. case "CallExpression":
  119. return node.callee.type === "Identifier" && node.callee.name === "Boolean" &&
  120. isReferenceToGlobalVariable(scope, node.callee) &&
  121. (node.arguments.length === 0 || isConstant(scope, node.arguments[0], true));
  122. case "UnaryExpression":
  123. return node.operator === "!" && isConstant(scope, node.argument, true);
  124. default:
  125. return false;
  126. }
  127. }
  128. /**
  129. * Test if an AST node will always give the same result when compared to a
  130. * boolean value. Note that comparison to boolean values is different than
  131. * truthiness.
  132. * https://262.ecma-international.org/5.1/#sec-11.9.3
  133. *
  134. * JavaScript `==` operator works by converting the boolean to `1` (true) or
  135. * `+0` (false) and then checks the values `==` equality to that number.
  136. * @param {Scope} scope The scope in which node was found.
  137. * @param {ASTNode} node The node to test.
  138. * @returns {boolean} Will `node` always coerce to the same boolean value?
  139. */
  140. function hasConstantLooseBooleanComparison(scope, node) {
  141. switch (node.type) {
  142. case "ObjectExpression":
  143. case "ClassExpression":
  144. /**
  145. * In theory objects like:
  146. *
  147. * `{toString: () => a}`
  148. * `{valueOf: () => a}`
  149. *
  150. * Or a classes like:
  151. *
  152. * `class { static toString() { return a } }`
  153. * `class { static valueOf() { return a } }`
  154. *
  155. * Are not constant verifiably when `inBooleanPosition` is
  156. * false, but it's an edge case we've opted not to handle.
  157. */
  158. return true;
  159. case "ArrayExpression": {
  160. const nonSpreadElements = node.elements.filter(e =>
  161. // Elements can be `null` in sparse arrays: `[,,]`;
  162. e !== null && e.type !== "SpreadElement");
  163. /*
  164. * Possible future direction if needed: We could check if the
  165. * single value would result in variable boolean comparison.
  166. * For now we will err on the side of caution since `[x]` could
  167. * evaluate to `[0]` or `[1]`.
  168. */
  169. return node.elements.length === 0 || nonSpreadElements.length > 1;
  170. }
  171. case "ArrowFunctionExpression":
  172. case "FunctionExpression":
  173. return true;
  174. case "UnaryExpression":
  175. if (node.operator === "void" || // Always returns `undefined`
  176. node.operator === "typeof" // All `typeof` strings, when coerced to number, are not 0 or 1.
  177. ) {
  178. return true;
  179. }
  180. if (node.operator === "!") {
  181. return isConstant(scope, node.argument, true);
  182. }
  183. /*
  184. * We won't try to reason about +, -, ~, or delete
  185. * In theory, for the mathematical operators, we could look at the
  186. * argument and try to determine if it coerces to a constant numeric
  187. * value.
  188. */
  189. return false;
  190. case "NewExpression": // Objects might have custom `.valueOf` or `.toString`.
  191. return false;
  192. case "CallExpression": {
  193. if (node.callee.type === "Identifier" &&
  194. node.callee.name === "Boolean" &&
  195. isReferenceToGlobalVariable(scope, node.callee)
  196. ) {
  197. return node.arguments.length === 0 || isConstant(scope, node.arguments[0], true);
  198. }
  199. return false;
  200. }
  201. case "Literal": // True or false, literals never change
  202. return true;
  203. case "Identifier":
  204. return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
  205. case "TemplateLiteral":
  206. /*
  207. * In theory we could try to check if the quasi are sufficient to
  208. * prove that the expression will always be true, but it would be
  209. * tricky to get right. For example: `000.${foo}000`
  210. */
  211. return node.expressions.length === 0;
  212. case "AssignmentExpression":
  213. if (node.operator === "=") {
  214. return hasConstantLooseBooleanComparison(scope, node.right);
  215. }
  216. /*
  217. * Handling short-circuiting assignment operators would require
  218. * walking the scope. We won't attempt that (for now...)
  219. *
  220. * The remaining assignment expressions all result in a numeric or
  221. * string (non-nullish) values which could be truthy or falsy:
  222. * "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="
  223. */
  224. return false;
  225. case "SequenceExpression": {
  226. const last = node.expressions.at(-1);
  227. return hasConstantLooseBooleanComparison(scope, last);
  228. }
  229. case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
  230. case "JSXFragment":
  231. return false;
  232. default:
  233. return false;
  234. }
  235. }
  236. /**
  237. * Test if an AST node will always give the same result when _strictly_ compared
  238. * to a boolean value. This can happen if the expression can never be boolean, or
  239. * if it is always the same boolean value.
  240. * @param {Scope} scope The scope in which the node was found.
  241. * @param {ASTNode} node The node to test
  242. * @returns {boolean} Will `node` always give the same result when compared to a
  243. * static boolean value?
  244. */
  245. function hasConstantStrictBooleanComparison(scope, node) {
  246. switch (node.type) {
  247. case "ObjectExpression": // Objects are not booleans
  248. case "ArrayExpression": // Arrays are not booleans
  249. case "ArrowFunctionExpression": // Functions are not booleans
  250. case "FunctionExpression":
  251. case "ClassExpression": // Classes are not booleans
  252. case "NewExpression": // Objects are not booleans
  253. case "TemplateLiteral": // Strings are not booleans
  254. case "Literal": // True, false, or not boolean, literals never change.
  255. case "UpdateExpression": // Numbers are not booleans
  256. return true;
  257. case "BinaryExpression":
  258. return NUMERIC_OR_STRING_BINARY_OPERATORS.has(node.operator);
  259. case "UnaryExpression": {
  260. if (node.operator === "delete") {
  261. return false;
  262. }
  263. if (node.operator === "!") {
  264. return isConstant(scope, node.argument, true);
  265. }
  266. /*
  267. * The remaining operators return either strings or numbers, neither
  268. * of which are boolean.
  269. */
  270. return true;
  271. }
  272. case "SequenceExpression": {
  273. const last = node.expressions.at(-1);
  274. return hasConstantStrictBooleanComparison(scope, last);
  275. }
  276. case "Identifier":
  277. return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
  278. case "AssignmentExpression":
  279. if (node.operator === "=") {
  280. return hasConstantStrictBooleanComparison(scope, node.right);
  281. }
  282. /*
  283. * Handling short-circuiting assignment operators would require
  284. * walking the scope. We won't attempt that (for now...)
  285. */
  286. if (isLogicalAssignmentOperator(node.operator)) {
  287. return false;
  288. }
  289. /*
  290. * The remaining assignment expressions all result in either a number
  291. * or a string, neither of which can ever be boolean.
  292. */
  293. return true;
  294. case "CallExpression": {
  295. if (node.callee.type !== "Identifier") {
  296. return false;
  297. }
  298. const functionName = node.callee.name;
  299. if (
  300. (functionName === "String" || functionName === "Number") &&
  301. isReferenceToGlobalVariable(scope, node.callee)
  302. ) {
  303. return true;
  304. }
  305. if (functionName === "Boolean" && isReferenceToGlobalVariable(scope, node.callee)) {
  306. return (
  307. node.arguments.length === 0 || isConstant(scope, node.arguments[0], true));
  308. }
  309. return false;
  310. }
  311. case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
  312. case "JSXFragment":
  313. return false;
  314. default:
  315. return false;
  316. }
  317. }
  318. /**
  319. * Test if an AST node will always result in a newly constructed object
  320. * @param {Scope} scope The scope in which the node was found.
  321. * @param {ASTNode} node The node to test
  322. * @returns {boolean} Will `node` always be new?
  323. */
  324. function isAlwaysNew(scope, node) {
  325. switch (node.type) {
  326. case "ObjectExpression":
  327. case "ArrayExpression":
  328. case "ArrowFunctionExpression":
  329. case "FunctionExpression":
  330. case "ClassExpression":
  331. return true;
  332. case "NewExpression": {
  333. if (node.callee.type !== "Identifier") {
  334. return false;
  335. }
  336. /*
  337. * All the built-in constructors are always new, but
  338. * user-defined constructors could return a sentinel
  339. * object.
  340. *
  341. * Catching these is especially useful for primitive constructors
  342. * which return boxed values, a surprising gotcha' in JavaScript.
  343. */
  344. return Object.hasOwn(ECMASCRIPT_GLOBALS, node.callee.name) &&
  345. isReferenceToGlobalVariable(scope, node.callee);
  346. }
  347. case "Literal":
  348. // Regular expressions are objects, and thus always new
  349. return typeof node.regex === "object";
  350. case "SequenceExpression": {
  351. const last = node.expressions.at(-1);
  352. return isAlwaysNew(scope, last);
  353. }
  354. case "AssignmentExpression":
  355. if (node.operator === "=") {
  356. return isAlwaysNew(scope, node.right);
  357. }
  358. return false;
  359. case "ConditionalExpression":
  360. return isAlwaysNew(scope, node.consequent) && isAlwaysNew(scope, node.alternate);
  361. case "JSXElement": // ESLint has a policy of not assuming any specific JSX behavior.
  362. case "JSXFragment":
  363. return false;
  364. default:
  365. return false;
  366. }
  367. }
  368. /**
  369. * Checks if one operand will cause the result to be constant.
  370. * @param {Scope} scope Scope in which the expression was found.
  371. * @param {ASTNode} a One side of the expression
  372. * @param {ASTNode} b The other side of the expression
  373. * @param {string} operator The binary expression operator
  374. * @returns {ASTNode | null} The node which will cause the expression to have a constant result.
  375. */
  376. function findBinaryExpressionConstantOperand(scope, a, b, operator) {
  377. if (operator === "==" || operator === "!=") {
  378. if (
  379. (isNullOrUndefined(scope, a) && hasConstantNullishness(scope, b, false)) ||
  380. (isStaticBoolean(scope, a) && hasConstantLooseBooleanComparison(scope, b))
  381. ) {
  382. return b;
  383. }
  384. } else if (operator === "===" || operator === "!==") {
  385. if (
  386. (isNullOrUndefined(scope, a) && hasConstantNullishness(scope, b, false)) ||
  387. (isStaticBoolean(scope, a) && hasConstantStrictBooleanComparison(scope, b))
  388. ) {
  389. return b;
  390. }
  391. }
  392. return null;
  393. }
  394. //------------------------------------------------------------------------------
  395. // Rule Definition
  396. //------------------------------------------------------------------------------
  397. /** @type {import('../shared/types').Rule} */
  398. module.exports = {
  399. meta: {
  400. type: "problem",
  401. docs: {
  402. description: "Disallow expressions where the operation doesn't affect the value",
  403. recommended: true,
  404. url: "https://eslint.org/docs/latest/rules/no-constant-binary-expression"
  405. },
  406. schema: [],
  407. messages: {
  408. constantBinaryOperand: "Unexpected constant binary expression. Compares constantly with the {{otherSide}}-hand side of the `{{operator}}`.",
  409. constantShortCircuit: "Unexpected constant {{property}} on the left-hand side of a `{{operator}}` expression.",
  410. alwaysNew: "Unexpected comparison to newly constructed object. These two values can never be equal.",
  411. bothAlwaysNew: "Unexpected comparison of two newly constructed objects. These two values can never be equal."
  412. }
  413. },
  414. create(context) {
  415. const sourceCode = context.sourceCode;
  416. return {
  417. LogicalExpression(node) {
  418. const { operator, left } = node;
  419. const scope = sourceCode.getScope(node);
  420. if ((operator === "&&" || operator === "||") && isConstant(scope, left, true)) {
  421. context.report({ node: left, messageId: "constantShortCircuit", data: { property: "truthiness", operator } });
  422. } else if (operator === "??" && hasConstantNullishness(scope, left, false)) {
  423. context.report({ node: left, messageId: "constantShortCircuit", data: { property: "nullishness", operator } });
  424. }
  425. },
  426. BinaryExpression(node) {
  427. const scope = sourceCode.getScope(node);
  428. const { right, left, operator } = node;
  429. const rightConstantOperand = findBinaryExpressionConstantOperand(scope, left, right, operator);
  430. const leftConstantOperand = findBinaryExpressionConstantOperand(scope, right, left, operator);
  431. if (rightConstantOperand) {
  432. context.report({ node: rightConstantOperand, messageId: "constantBinaryOperand", data: { operator, otherSide: "left" } });
  433. } else if (leftConstantOperand) {
  434. context.report({ node: leftConstantOperand, messageId: "constantBinaryOperand", data: { operator, otherSide: "right" } });
  435. } else if (operator === "===" || operator === "!==") {
  436. if (isAlwaysNew(scope, left)) {
  437. context.report({ node: left, messageId: "alwaysNew" });
  438. } else if (isAlwaysNew(scope, right)) {
  439. context.report({ node: right, messageId: "alwaysNew" });
  440. }
  441. } else if (operator === "==" || operator === "!=") {
  442. /*
  443. * If both sides are "new", then both sides are objects and
  444. * therefore they will be compared by reference even with `==`
  445. * equality.
  446. */
  447. if (isAlwaysNew(scope, left) && isAlwaysNew(scope, right)) {
  448. context.report({ node: left, messageId: "bothAlwaysNew" });
  449. }
  450. }
  451. }
  452. /*
  453. * In theory we could handle short-circuiting assignment operators,
  454. * for some constant values, but that would require walking the
  455. * scope to find the value of the variable being assigned. This is
  456. * dependant on https://github.com/eslint/eslint/issues/13776
  457. *
  458. * AssignmentExpression() {},
  459. */
  460. };
  461. }
  462. };