Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fix: fix false positives of no-new-func (#13333)
* Fix: fix false positives of no-new-func

* add more tests

* fix false positive

* fix
  • Loading branch information
g-plane committed May 22, 2020
1 parent 611c676 commit e3e4c41
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 20 deletions.
41 changes: 22 additions & 19 deletions lib/rules/no-new-func.js
Expand Up @@ -29,26 +29,29 @@ module.exports = {

create(context) {

//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------

/**
* Reports a node.
* @param {ASTNode} node The node to report
* @returns {void}
* @private
*/
function report(node) {
context.report({
node,
messageId: "noFunctionConstructor"
});
}

return {
"NewExpression[callee.name = 'Function']": report,
"CallExpression[callee.name = 'Function']": report
"Program:exit"() {
const globalScope = context.getScope();
const variable = globalScope.set.get("Function");

if (variable && variable.defs.length === 0) {
variable.references.forEach(ref => {
const node = ref.identifier;
const { parent } = node;

if (
parent &&
(parent.type === "NewExpression" || parent.type === "CallExpression") &&
node === parent.callee
) {
context.report({
node: parent,
messageId: "noFunctionConstructor"
});
}
});
}
}
};

}
Expand Down
36 changes: 35 additions & 1 deletion tests/lib/rules/no-new-func.js
Expand Up @@ -21,7 +21,24 @@ const ruleTester = new RuleTester();
ruleTester.run("no-new-func", rule, {
valid: [
"var a = new _function(\"b\", \"c\", \"return b+c\");",
"var a = _function(\"b\", \"c\", \"return b+c\");"
"var a = _function(\"b\", \"c\", \"return b+c\");",
{
code: "class Function {}; new Function()",
parserOptions: {
ecmaVersion: 2015
}
},
{
code: "const fn = () => { class Function {}; new Function() }",
parserOptions: {
ecmaVersion: 2015
}
},
"function Function() {}; Function()",
"var fn = function () { function Function() {}; Function() }",
"var x = function Function() { Function(); }",
"call(Function)",
"new Class(Function)"
],
invalid: [
{
Expand All @@ -37,6 +54,23 @@ ruleTester.run("no-new-func", rule, {
messageId: "noFunctionConstructor",
type: "CallExpression"
}]
},
{
code: "const fn = () => { class Function {} }; new Function('', '')",
parserOptions: {
ecmaVersion: 2015
},
errors: [{
messageId: "noFunctionConstructor",
type: "NewExpression"
}]
},
{
code: "var fn = function () { function Function() {} }; Function('', '')",
errors: [{
messageId: "noFunctionConstructor",
type: "CallExpression"
}]
}
]
});

0 comments on commit e3e4c41

Please sign in to comment.