From b146b51b6f5d39a56274dcac6f92295366274ca9 Mon Sep 17 00:00:00 2001 From: Sean Gray Date: Mon, 23 Sep 2019 18:03:55 -0500 Subject: [PATCH] Fix: no-constant-condition doesn't introspect arrays (fixes #12225) --- lib/rules/no-constant-condition.js | 16 ++++++++++++++- tests/lib/rules/no-constant-condition.js | 26 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/lib/rules/no-constant-condition.js b/lib/rules/no-constant-condition.js index d6d04174298c..06c35f6aab45 100644 --- a/lib/rules/no-constant-condition.js +++ b/lib/rules/no-constant-condition.js @@ -90,14 +90,28 @@ module.exports = { * @private */ function isConstant(node, inBooleanPosition) { + + /* + * Bug in espree (#425) causes [,] to return children of null + * so we need to check for existance until that is fixed + */ + if (!node) { + return true; + } switch (node.type) { case "Literal": case "ArrowFunctionExpression": case "FunctionExpression": case "ObjectExpression": - case "ArrayExpression": return true; + case "ArrayExpression": { + if (inBooleanPosition) { + return true; + } + return node.elements.every(element => isConstant(element, false)); + } + case "UnaryExpression": if (node.operator === "void") { return true; diff --git a/tests/lib/rules/no-constant-condition.js b/tests/lib/rules/no-constant-condition.js index a5ede35cc8ea..cfc2134eb4b2 100644 --- a/tests/lib/rules/no-constant-condition.js +++ b/tests/lib/rules/no-constant-condition.js @@ -73,6 +73,14 @@ ruleTester.run("no-constant-condition", rule, { "if ((key || 'k') in obj) {}", "if ((foo || {}) instanceof obj) {}", + // #12225 + "if ('' + [y] === '' + [ty]) {}", + "if ('a' === '' + [ty]) {}", + "if ('' + [y, m, d] === 'a') {}", + "if ('' + [y, 'm'] === '' + [ty, 'tm']) {}", + "if ('' + [y, 'm'] === '' + ['ty']) {}", + "if ([,] in\n\n($2))\n ;\nelse\n ;", + // { checkLoops: false } { code: "while(true);", options: [{ checkLoops: false }] }, { code: "for(;true;);", options: [{ checkLoops: false }] }, @@ -183,6 +191,24 @@ ruleTester.run("no-constant-condition", rule, { { code: "function* foo() { for (let foo = 1 + 2 + 3 + (yield); true; baz) {}}", errors: [{ messageId: "unexpected", type: "Literal" }] + }, + + // #12225 + { + code: "if([a]) {}", + errors: [{ messageId: "unexpected", type: "ArrayExpression" }] + }, + { + code: "if([]) {}", + errors: [{ messageId: "unexpected", type: "ArrayExpression" }] + }, + { + code: "if(''+['a']) {}", + errors: [{ messageId: "unexpected", type: "BinaryExpression" }] + }, + { + code: "if(''+[]) {}", + errors: [{ messageId: "unexpected", type: "BinaryExpression" }] } ] });