no-constant-binary-expression.js 20 KB

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