Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add suggestions for redundant wrapping in prefer-regex-literals #16658

Merged
merged 9 commits into from Jan 3, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
114 changes: 103 additions & 11 deletions lib/rules/prefer-regex-literals.js
Expand Up @@ -146,6 +146,7 @@ module.exports = {
messages: {
unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor.",
replaceWithLiteral: "Replace with an equivalent regular expression literal.",
replaceWithLiteralAndFlags: "Replace with an equivalent regular expression literal with flags.",
yeonjuan marked this conversation as resolved.
Show resolved Hide resolved
unexpectedRedundantRegExp: "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.",
unexpectedRedundantRegExpWithFlags: "Use regular expression literal with flags instead of the 'RegExp' constructor."
}
Expand Down Expand Up @@ -258,6 +259,8 @@ module.exports = {
return Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION);
}

const regexppEcmaVersion = getRegexppEcmaVersion(context.languageOptions.ecmaVersion);

/**
* Makes a character escaped or else returns null.
* @param {string} character The character to escape.
Expand Down Expand Up @@ -293,6 +296,52 @@ module.exports = {
}
}

/**
* Checks whether the given regex and flags are valid for the ecma version or not.
* @param {string} pattern The regex pattern to check.
* @param {string | undefined} flags The regex flags to check.
* @returns {boolean} True if the given regex pattern and flags are valid for the ecma version.
*/
function isValidRegexForEcmaVersion(pattern, flags) {
const validator = new RegExpValidator({ ecmaVersion: regexppEcmaVersion });

try {
validator.validatePattern(pattern, 0, pattern.length, flags ? flags.includes("u") : false);
if (flags) {
validator.validateFlags(flags);
}
return true;
} catch {
return false;
}
}

/**
* Checks whether two given regex flags contain the same flags or not.
* @param {string} flagsA The regex flags.
* @param {string} flagsB The regex flags.
* @returns {boolean} True if two regex flags contain same flags.
*/
function areFlagsEqual(flagsA, flagsB) {
return [...flagsA].sort().join("") === [...flagsB].sort().join("");
}


/**
* Merges two regex flags.
* @param {string} flagsA The regex flags.
* @param {string} flagsB The regex flags.
* @returns {string} The merged regex flags.
*/
function mergeRegexFlags(flagsA, flagsB) {
const flagsSet = new Set([
...flagsA,
...flagsB
]);

return [...flagsSet].join("");
}

return {
Program() {
const scope = context.getScope();
Expand All @@ -306,10 +355,61 @@ module.exports = {

for (const { node } of tracker.iterateGlobalReferences(traceMap)) {
if (disallowRedundantWrapping && isUnnecessarilyWrappedRegexLiteral(node)) {
const regexNode = node.arguments[0];

if (node.arguments.length === 2) {
context.report({ node, messageId: "unexpectedRedundantRegExpWithFlags" });
const outputs = [];

if (sourceCode.getCommentsInside(node).length === 0) {
const literalFlags = regexNode.regex.flags || "";
const argFlags = getStringValue(node.arguments[1]) || "";

if (isValidRegexForEcmaVersion(regexNode.regex.pattern, argFlags)) {
outputs.push(`/${regexNode.regex.pattern}/${argFlags}`);
}

if (literalFlags && argFlags) {
const mergedFlags = mergeRegexFlags(literalFlags, argFlags);

if (
!areFlagsEqual(mergedFlags, argFlags) &&
isValidRegexForEcmaVersion(regexNode.regex.pattern, mergedFlags)
) {
outputs.push(`/${regexNode.regex.pattern}/${mergedFlags}`);
}
}
}

context.report({
node,
messageId: "unexpectedRedundantRegExpWithFlags",
suggest: outputs.map(output => ({
messageId: "replaceWithLiteralAndFlags",
fix(fixer) {
return fixer.replaceText(node, output);
}
}))
});
} else {
context.report({ node, messageId: "unexpectedRedundantRegExp" });
const outputs = [];

if (
sourceCode.getCommentsInside(node).length === 0 &&
isValidRegexForEcmaVersion(regexNode.regex.pattern, regexNode.regex.flags)
) {
outputs.push(sourceCode.getText(regexNode));
}

context.report({
node,
messageId: "unexpectedRedundantRegExp",
suggest: outputs.map(output => ({
messageId: "replaceWithLiteral",
fix(fixer) {
return fixer.replaceText(node, output);
}
}))
});
}
} else if (hasOnlyStaticStringArguments(node)) {
let regexContent = getStringValue(node.arguments[0]);
Expand All @@ -320,15 +420,7 @@ module.exports = {
flags = getStringValue(node.arguments[1]);
}

const regexppEcmaVersion = getRegexppEcmaVersion(context.languageOptions.ecmaVersion);
const RegExpValidatorInstance = new RegExpValidator({ ecmaVersion: regexppEcmaVersion });

try {
RegExpValidatorInstance.validatePattern(regexContent, 0, regexContent.length, flags ? flags.includes("u") : false);
if (flags) {
RegExpValidatorInstance.validateFlags(flags);
}
} catch {
if (!isValidRegexForEcmaVersion(regexContent, flags)) {
noFix = true;
}

Expand Down