no-constant-condition.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. // node.elements can return null values in the case of sparse arrays ex. [,]
  77. if (!node) {
  78. return true;
  79. }
  80. switch (node.type) {
  81. case "Literal":
  82. case "ArrowFunctionExpression":
  83. case "FunctionExpression":
  84. case "ObjectExpression":
  85. return true;
  86. case "TemplateLiteral":
  87. return (inBooleanPosition && node.quasis.some(quasi => quasi.value.cooked.length)) ||
  88. node.expressions.every(exp => isConstant(exp, inBooleanPosition));
  89. case "ArrayExpression": {
  90. if (node.parent.type === "BinaryExpression" && node.parent.operator === "+") {
  91. return node.elements.every(element => isConstant(element, false));
  92. }
  93. return true;
  94. }
  95. case "UnaryExpression":
  96. if (node.operator === "void") {
  97. return true;
  98. }
  99. return (node.operator === "typeof" && inBooleanPosition) ||
  100. isConstant(node.argument, true);
  101. case "BinaryExpression":
  102. return isConstant(node.left, false) &&
  103. isConstant(node.right, false) &&
  104. node.operator !== "in";
  105. case "LogicalExpression": {
  106. const isLeftConstant = isConstant(node.left, inBooleanPosition);
  107. const isRightConstant = isConstant(node.right, inBooleanPosition);
  108. const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator));
  109. const isRightShortCircuit = (isRightConstant && isLogicalIdentity(node.right, node.operator));
  110. return (isLeftConstant && isRightConstant) ||
  111. (
  112. // in the case of an "OR", we need to know if the right constant value is truthy
  113. node.operator === "||" &&
  114. isRightConstant &&
  115. node.right.value &&
  116. (
  117. !node.parent ||
  118. node.parent.type !== "BinaryExpression" ||
  119. !(EQUALITY_OPERATORS.includes(node.parent.operator) || RELATIONAL_OPERATORS.includes(node.parent.operator))
  120. )
  121. ) ||
  122. isLeftShortCircuit ||
  123. isRightShortCircuit;
  124. }
  125. case "AssignmentExpression":
  126. return (node.operator === "=") && isConstant(node.right, inBooleanPosition);
  127. case "SequenceExpression":
  128. return isConstant(node.expressions[node.expressions.length - 1], inBooleanPosition);
  129. // no default
  130. }
  131. return false;
  132. }
  133. /**
  134. * Tracks when the given node contains a constant condition.
  135. * @param {ASTNode} node The AST node to check.
  136. * @returns {void}
  137. * @private
  138. */
  139. function trackConstantConditionLoop(node) {
  140. if (node.test && isConstant(node.test, true)) {
  141. loopsInCurrentScope.add(node);
  142. }
  143. }
  144. /**
  145. * Reports when the set contains the given constant condition node
  146. * @param {ASTNode} node The AST node to check.
  147. * @returns {void}
  148. * @private
  149. */
  150. function checkConstantConditionLoopInSet(node) {
  151. if (loopsInCurrentScope.has(node)) {
  152. loopsInCurrentScope.delete(node);
  153. context.report({ node: node.test, messageId: "unexpected" });
  154. }
  155. }
  156. /**
  157. * Reports when the given node contains a constant condition.
  158. * @param {ASTNode} node The AST node to check.
  159. * @returns {void}
  160. * @private
  161. */
  162. function reportIfConstant(node) {
  163. if (node.test && isConstant(node.test, true)) {
  164. context.report({ node: node.test, messageId: "unexpected" });
  165. }
  166. }
  167. /**
  168. * Stores current set of constant loops in loopSetStack temporarily
  169. * and uses a new set to track constant loops
  170. * @returns {void}
  171. * @private
  172. */
  173. function enterFunction() {
  174. loopSetStack.push(loopsInCurrentScope);
  175. loopsInCurrentScope = new Set();
  176. }
  177. /**
  178. * Reports when the set still contains stored constant conditions
  179. * @returns {void}
  180. * @private
  181. */
  182. function exitFunction() {
  183. loopsInCurrentScope = loopSetStack.pop();
  184. }
  185. /**
  186. * Checks node when checkLoops option is enabled
  187. * @param {ASTNode} node The AST node to check.
  188. * @returns {void}
  189. * @private
  190. */
  191. function checkLoop(node) {
  192. if (checkLoops) {
  193. trackConstantConditionLoop(node);
  194. }
  195. }
  196. //--------------------------------------------------------------------------
  197. // Public
  198. //--------------------------------------------------------------------------
  199. return {
  200. ConditionalExpression: reportIfConstant,
  201. IfStatement: reportIfConstant,
  202. WhileStatement: checkLoop,
  203. "WhileStatement:exit": checkConstantConditionLoopInSet,
  204. DoWhileStatement: checkLoop,
  205. "DoWhileStatement:exit": checkConstantConditionLoopInSet,
  206. ForStatement: checkLoop,
  207. "ForStatement > .test": node => checkLoop(node.parent),
  208. "ForStatement:exit": checkConstantConditionLoopInSet,
  209. FunctionDeclaration: enterFunction,
  210. "FunctionDeclaration:exit": exitFunction,
  211. FunctionExpression: enterFunction,
  212. "FunctionExpression:exit": exitFunction,
  213. YieldExpression: () => loopsInCurrentScope.clear()
  214. };
  215. }
  216. };