Skip to content

Commit

Permalink
Update: prefer-regex-literal detects regex literals passed to RegExp (f…
Browse files Browse the repository at this point in the history
…ixes #12840)
  • Loading branch information
lo1tuma committed Jan 29, 2020
1 parent 03a69db commit 8b42995
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
27 changes: 23 additions & 4 deletions lib/rules/prefer-regex-literals.js
Expand Up @@ -25,6 +25,15 @@ function isStringLiteral(node) {
return node.type === "Literal" && typeof node.value === "string";
}

/**
* Determines whether the given node is a regex literal.
* @param {ASTNode} node Node to check.
* @returns {boolean} True if the node is a regex literal.
*/
function isRegexLiteral(node) {
return node.type === "Literal" && Object.prototype.hasOwnProperty.call(node, "regex");
}

/**
* Determines whether the given node is a template literal without expressions.
* @param {ASTNode} node Node to check.
Expand Down Expand Up @@ -98,6 +107,15 @@ module.exports = {
isStringRawTaggedStaticTemplateLiteral(node);
}

/**
* Determines whether the given node is considered to be a static string literal or a regex literal
* @param {ASTNode} node Node to check.
* @returns {boolean} True if the node is a static string or a regex literal
*/
function isStaticPattern(node) {
return isStaticString(node) || isRegexLiteral(node);
}

return {
Program() {
const scope = context.getScope();
Expand All @@ -112,10 +130,11 @@ module.exports = {
for (const { node } of tracker.iterateGlobalReferences(traceMap)) {
const args = node.arguments;

if (
(args.length === 1 || args.length === 2) &&
args.every(isStaticString)
) {
if (args.length === 1 && isStaticPattern(args[0])) {
context.report({ node, messageId: "unexpectedRegExp" });
}

if (args.length === 2 && isStaticPattern(args[0]) && isStaticString(args[1])) {
context.report({ node, messageId: "unexpectedRegExp" });
}
}
Expand Down
9 changes: 9 additions & 0 deletions tests/lib/rules/prefer-regex-literals.js
Expand Up @@ -41,6 +41,7 @@ ruleTester.run("prefer-regex-literals", rule, {
"new RegExp(String.raw`a${''}c`);",
"new RegExp('a' + 'b')",
"RegExp(1)",
"new RegExp(/a/, flags);",

// invalid number of arguments
"new RegExp;",
Expand Down Expand Up @@ -177,6 +178,14 @@ ruleTester.run("prefer-regex-literals", rule, {
{
code: "RegExp('a', String.raw`g`);",
errors: [{ messageId: "unexpectedRegExp", type: "CallExpression" }]
},
{
code: "new RegExp(/a/);",
errors: [{ messageId: "unexpectedRegExp", type: "NewExpression", line: 1, column: 1 }]
},
{
code: "new RegExp(/a/, 'u');",
errors: [{ messageId: "unexpectedRegExp", type: "NewExpression", line: 1, column: 1 }]
}
]
});

0 comments on commit 8b42995

Please sign in to comment.