no-constant-condition.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. /**
  2. * @fileoverview Rule to flag use constant conditions
  3. * @author Christian Schulz <http://rndm.de>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. const EQUALITY_OPERATORS = ["===", "!==", "==", "!="];
  10. const RELATIONAL_OPERATORS = [">", "<", ">=", "<=", "in", "instanceof"];
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. module.exports = {
  15. meta: {
  16. type: "problem",
  17. docs: {
  18. description: "disallow constant expressions in conditions",
  19. category: "Possible Errors",
  20. recommended: true,
  21. url: "https://eslint.org/docs/rules/no-constant-condition"
  22. },
  23. schema: [
  24. {
  25. type: "object",
  26. properties: {
  27. checkLoops: {
  28. type: "boolean",
  29. default: true
  30. }
  31. },
  32. additionalProperties: false
  33. }
  34. ],
  35. messages: {
  36. unexpected: "Unexpected constant condition."
  37. }
  38. },
  39. create(context) {
  40. const options = context.options[0] || {},
  41. checkLoops = options.checkLoops !== false,
  42. loopSetStack = [];
  43. let loopsInCurrentScope = new Set();
  44. //--------------------------------------------------------------------------
  45. // Helpers
  46. //--------------------------------------------------------------------------
  47. /**
  48. * Checks if a branch node of LogicalExpression short circuits the whole condition
  49. * @param {ASTNode} node The branch of main condition which needs to be checked
  50. * @param {string} operator The operator of the main LogicalExpression.
  51. * @returns {boolean} true when condition short circuits whole condition
  52. */
  53. function isLogicalIdentity(node, operator) {
  54. switch (node.type) {
  55. case "Literal":
  56. return (operator === "||" && node.value === true) ||
  57. (operator === "&&" && node.value === false);
  58. case "UnaryExpression":
  59. return (operator === "&&" && node.operator === "void");
  60. case "LogicalExpression":
  61. return isLogicalIdentity(node.left, node.operator) ||
  62. isLogicalIdentity(node.right, node.operator);
  63. // no default
  64. }
  65. return false;
  66. }
  67. /**
  68. * Checks if a node has a constant truthiness value.
  69. * @param {ASTNode} node The AST node to check.
  70. * @param {boolean} inBooleanPosition `false` if checking branch of a condition.
  71. * `true` in all other cases
  72. * @returns {Bool} true when node's truthiness is constant
  73. * @private
  74. */
  75. function isConstant(node, inBooleanPosition) {
  76. switch (node.type) {
  77. case "Literal":
  78. case "ArrowFunctionExpression":
  79. case "FunctionExpression":
  80. case "ObjectExpression":
  81. case "ArrayExpression":
  82. return true;
  83. case "UnaryExpression":
  84. if (node.operator === "void") {
  85. return true;
  86. }
  87. return (node.operator === "typeof" && inBooleanPosition) ||
  88. isConstant(node.argument, true);
  89. case "BinaryExpression":
  90. return isConstant(node.left, false) &&
  91. isConstant(node.right, false) &&
  92. node.operator !== "in";
  93. case "LogicalExpression": {
  94. const isLeftConstant = isConstant(node.left, inBooleanPosition);
  95. const isRightConstant = isConstant(node.right, inBooleanPosition);
  96. const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator));
  97. const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator));
  98. return (isLeftConstant && isRightConstant) ||
  99. (
  100. // in the case of an "OR", we need to know if the right constant value is truthy
  101. node.operator === "||" &&
  102. isRightConstant &&
  103. node.right.value &&
  104. (
  105. !node.parent ||
  106. node.parent.type !== "BinaryExpression" ||
  107. !(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator))
  108. )
  109. ) ||
  110. isLeftShortCircuit ||
  111. isRightShortCircuit;
  112. }
  113. case "AssignmentExpression":
  114. return (node.operator === "=") && isConstant(node.right, inBooleanPosition);
  115. case "SequenceExpression":
  116. return isConstant(node.expressions[node.expressions.length - 1], inBooleanPosition);
  117. // no default
  118. }
  119. return false;
  120. }
  121. /**
  122. * Tracks when the given node contains a constant condition.
  123. * @param {ASTNode} node The AST node to check.
  124. * @returns {void}
  125. * @private
  126. */
  127. function trackConstantConditionLoop(node) {
  128. if (node.test && isConstant(node.test, true)) {
  129. loopsInCurrentScope.add(node);
  130. }
  131. }
  132. /**
  133. * Reports when the set contains the given constant condition node
  134. * @param {ASTNode} node The AST node to check.
  135. * @returns {void}
  136. * @private
  137. */
  138. function checkConstantConditionLoopInSet(node) {
  139. if (loopsInCurrentScope.has(node)) {
  140. loopsInCurrentScope.delete(node);
  141. context.report({ node: node.test, messageId: "unexpected" });
  142. }
  143. }
  144. /**
  145. * Reports when the given node contains a constant condition.
  146. * @param {ASTNode} node The AST node to check.
  147. * @returns {void}
  148. * @private
  149. */
  150. function reportIfConstant(node) {
  151. if (node.test && isConstant(node.test, true)) {
  152. context.report({ node: node.test, messageId: "unexpected" });
  153. }
  154. }
  155. /**
  156. * Stores current set of constant loops in loopSetStack temporarily
  157. * and uses a new set to track constant loops
  158. * @returns {void}
  159. * @private
  160. */
  161. function enterFunction() {
  162. loopSetStack.push(loopsInCurrentScope);
  163. loopsInCurrentScope = new Set();
  164. }
  165. /**
  166. * Reports when the set still contains stored constant conditions
  167. * @returns {void}
  168. * @private
  169. */
  170. function exitFunction() {
  171. loopsInCurrentScope = loopSetStack.pop();
  172. }
  173. /**
  174. * Checks node when checkLoops option is enabled
  175. * @param {ASTNode} node The AST node to check.
  176. * @returns {void}
  177. * @private
  178. */
  179. function checkLoop(node) {
  180. if (checkLoops) {
  181. trackConstantConditionLoop(node);
  182. }
  183. }
  184. //--------------------------------------------------------------------------
  185. // Public
  186. //--------------------------------------------------------------------------
  187. return {
  188. ConditionalExpression: reportIfConstant,
  189. IfStatement: reportIfConstant,
  190. WhileStatement: checkLoop,
  191. "WhileStatement:exit": checkConstantConditionLoopInSet,
  192. DoWhileStatement: checkLoop,
  193. "DoWhileStatement:exit": checkConstantConditionLoopInSet,
  194. ForStatement: checkLoop,
  195. "ForStatement > .test": node => checkLoop(node.parent),
  196. "ForStatement:exit": checkConstantConditionLoopInSet,
  197. FunctionDeclaration: enterFunction,
  198. "FunctionDeclaration:exit": exitFunction,
  199. FunctionExpression: enterFunction,
  200. "FunctionExpression:exit": exitFunction,
  201. YieldExpression: () => loopsInCurrentScope.clear()
  202. };
  203. }
  204. };