1 | /**
|
2 | * @fileoverview Rule to flag use constant conditions
|
3 | * @author Christian Schulz <http://rndm.de>
|
4 | * @copyright 2014 Christian Schulz. All rights reserved.
|
5 | */
|
6 |
|
7 | ;
|
8 |
|
9 | //------------------------------------------------------------------------------
|
10 | // Rule Definition
|
11 | //------------------------------------------------------------------------------
|
12 |
|
13 | module.exports = function(context) {
|
14 |
|
15 | //--------------------------------------------------------------------------
|
16 | // Helpers
|
17 | //--------------------------------------------------------------------------
|
18 |
|
19 | /**
|
20 | * Checks if a node has a constant truthiness value.
|
21 | * @param {ASTNode} node The AST node to check.
|
22 | * @returns {Bool} true when node's truthiness is constant
|
23 | * @private
|
24 | */
|
25 | function isConstant(node) {
|
26 | switch (node.type) {
|
27 | case "Literal":
|
28 | case "ArrowFunctionExpression":
|
29 | case "FunctionExpression":
|
30 | case "ObjectExpression":
|
31 | case "ArrayExpression":
|
32 | return true;
|
33 | case "UnaryExpression":
|
34 | return isConstant(node.argument);
|
35 | case "BinaryExpression":
|
36 | case "LogicalExpression":
|
37 | return isConstant(node.left) && isConstant(node.right) && node.operator !== "in";
|
38 | case "AssignmentExpression":
|
39 | return (node.operator === "=") && isConstant(node.right);
|
40 | case "SequenceExpression":
|
41 | return isConstant(node.expressions[node.expressions.length - 1]);
|
42 | // no default
|
43 | }
|
44 | return false;
|
45 | }
|
46 |
|
47 | /**
|
48 | * Reports when the given node contains a constant condition.
|
49 | * @param {ASTNode} node The AST node to check.
|
50 | * @returns {void}
|
51 | * @private
|
52 | */
|
53 | function checkConstantCondition(node) {
|
54 | if (node.test && isConstant(node.test)) {
|
55 | context.report(node, "Unexpected constant condition.");
|
56 | }
|
57 | }
|
58 |
|
59 | //--------------------------------------------------------------------------
|
60 | // Public
|
61 | //--------------------------------------------------------------------------
|
62 |
|
63 | return {
|
64 | "ConditionalExpression": checkConstantCondition,
|
65 | "IfStatement": checkConstantCondition,
|
66 | "WhileStatement": checkConstantCondition,
|
67 | "DoWhileStatement": checkConstantCondition,
|
68 | "ForStatement": checkConstantCondition
|
69 | };
|
70 |
|
71 | };
|
72 |
|
73 | module.exports.schema = [];
|