Skip to content
Permalink
Browse files

Fix: func-name-matching crash on non-string literal computed keys (#8246

)

* Fix: func-name-matching crash on non-string literal computed keys

In order to detect whether it should require a function name match, the `func-name-matching` rule checks to see if a computed object key is a string literal, and if so, it performs operations on the value of the string literal. However, the rule was previously only verifying that the computed object key was a literal, without verifying that it was a *string* literal. As a result, if other literals (e.g. `null`) were used as computed object keys, the rule would crash. This fix updates the rule to check that the object key is a *string* literal.

* Add additional test cases for literals
  • Loading branch information...
not-an-aardvark committed Mar 16, 2017
1 parent 7276e6d commit a34b9c4c7558156e54af11fef6e053dbdd366857
Showing with 39 additions and 2 deletions.
  1. +11 −2 lib/rules/func-name-matching.js
  2. +28 −0 tests/lib/rules/func-name-matching.js
@@ -132,6 +132,15 @@ module.exports = {
});
}

/**
* Determines whether a given node is a string literal
* @param {ASTNode} node The node to check
* @returns {boolean} `true` if the node is a string literal
*/
function isStringLiteral(node) {
return node.type === "Literal" && typeof node.value === "string";
}

//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
@@ -164,13 +173,13 @@ module.exports = {
},

Property(node) {
if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && node.key.type !== "Literal") {
if (node.value.type !== "FunctionExpression" || !node.value.id || node.computed && !isStringLiteral(node.key)) {
return;
}
if (node.key.type === "Identifier" && shouldWarn(node.key.name, node.value.id.name)) {
report(node, node.key.name, node.value.id.name, true);
} else if (
node.key.type === "Literal" &&
isStringLiteral(node.key) &&
isIdentifier(node.key.value, ecmaVersion) &&
shouldWarn(node.key.value, node.value.id.name)
) {
@@ -117,6 +117,34 @@ ruleTester.run("func-name-matching", rule, {
{
code: "({[foo]: function bar() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[null]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[1]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[true]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[`x`]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[/abc/]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[[1, 2, 3]]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
},
{
code: "({[{x: 1}]: function foo() {}})",
parserOptions: { ecmaVersion: 6 }
}
],
invalid: [

0 comments on commit a34b9c4

Please sign in to comment.
You can’t perform that action at this time.