1 | /**
|
---|
2 | * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals
|
---|
3 | * @author Milos Djermanovic
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | //------------------------------------------------------------------------------
|
---|
9 | // Requirements
|
---|
10 | //------------------------------------------------------------------------------
|
---|
11 |
|
---|
12 | const astUtils = require("./utils/ast-utils");
|
---|
13 | const { CALL, CONSTRUCT, ReferenceTracker, findVariable } = require("@eslint-community/eslint-utils");
|
---|
14 | const { RegExpValidator, visitRegExpAST, RegExpParser } = require("@eslint-community/regexpp");
|
---|
15 | const { canTokensBeAdjacent } = require("./utils/ast-utils");
|
---|
16 | const { REGEXPP_LATEST_ECMA_VERSION } = require("./utils/regular-expressions");
|
---|
17 |
|
---|
18 | //------------------------------------------------------------------------------
|
---|
19 | // Helpers
|
---|
20 | //------------------------------------------------------------------------------
|
---|
21 |
|
---|
22 | /**
|
---|
23 | * Determines whether the given node is a string literal.
|
---|
24 | * @param {ASTNode} node Node to check.
|
---|
25 | * @returns {boolean} True if the node is a string literal.
|
---|
26 | */
|
---|
27 | function isStringLiteral(node) {
|
---|
28 | return node.type === "Literal" && typeof node.value === "string";
|
---|
29 | }
|
---|
30 |
|
---|
31 | /**
|
---|
32 | * Determines whether the given node is a regex literal.
|
---|
33 | * @param {ASTNode} node Node to check.
|
---|
34 | * @returns {boolean} True if the node is a regex literal.
|
---|
35 | */
|
---|
36 | function isRegexLiteral(node) {
|
---|
37 | return node.type === "Literal" && Object.prototype.hasOwnProperty.call(node, "regex");
|
---|
38 | }
|
---|
39 |
|
---|
40 | const validPrecedingTokens = new Set([
|
---|
41 | "(",
|
---|
42 | ";",
|
---|
43 | "[",
|
---|
44 | ",",
|
---|
45 | "=",
|
---|
46 | "+",
|
---|
47 | "*",
|
---|
48 | "-",
|
---|
49 | "?",
|
---|
50 | "~",
|
---|
51 | "%",
|
---|
52 | "**",
|
---|
53 | "!",
|
---|
54 | "typeof",
|
---|
55 | "instanceof",
|
---|
56 | "&&",
|
---|
57 | "||",
|
---|
58 | "??",
|
---|
59 | "return",
|
---|
60 | "...",
|
---|
61 | "delete",
|
---|
62 | "void",
|
---|
63 | "in",
|
---|
64 | "<",
|
---|
65 | ">",
|
---|
66 | "<=",
|
---|
67 | ">=",
|
---|
68 | "==",
|
---|
69 | "===",
|
---|
70 | "!=",
|
---|
71 | "!==",
|
---|
72 | "<<",
|
---|
73 | ">>",
|
---|
74 | ">>>",
|
---|
75 | "&",
|
---|
76 | "|",
|
---|
77 | "^",
|
---|
78 | ":",
|
---|
79 | "{",
|
---|
80 | "=>",
|
---|
81 | "*=",
|
---|
82 | "<<=",
|
---|
83 | ">>=",
|
---|
84 | ">>>=",
|
---|
85 | "^=",
|
---|
86 | "|=",
|
---|
87 | "&=",
|
---|
88 | "??=",
|
---|
89 | "||=",
|
---|
90 | "&&=",
|
---|
91 | "**=",
|
---|
92 | "+=",
|
---|
93 | "-=",
|
---|
94 | "/=",
|
---|
95 | "%=",
|
---|
96 | "/",
|
---|
97 | "do",
|
---|
98 | "break",
|
---|
99 | "continue",
|
---|
100 | "debugger",
|
---|
101 | "case",
|
---|
102 | "throw"
|
---|
103 | ]);
|
---|
104 |
|
---|
105 |
|
---|
106 | //------------------------------------------------------------------------------
|
---|
107 | // Rule Definition
|
---|
108 | //------------------------------------------------------------------------------
|
---|
109 |
|
---|
110 | /** @type {import('../shared/types').Rule} */
|
---|
111 | module.exports = {
|
---|
112 | meta: {
|
---|
113 | type: "suggestion",
|
---|
114 |
|
---|
115 | docs: {
|
---|
116 | description: "Disallow use of the `RegExp` constructor in favor of regular expression literals",
|
---|
117 | recommended: false,
|
---|
118 | url: "https://eslint.org/docs/latest/rules/prefer-regex-literals"
|
---|
119 | },
|
---|
120 |
|
---|
121 | hasSuggestions: true,
|
---|
122 |
|
---|
123 | schema: [
|
---|
124 | {
|
---|
125 | type: "object",
|
---|
126 | properties: {
|
---|
127 | disallowRedundantWrapping: {
|
---|
128 | type: "boolean",
|
---|
129 | default: false
|
---|
130 | }
|
---|
131 | },
|
---|
132 | additionalProperties: false
|
---|
133 | }
|
---|
134 | ],
|
---|
135 |
|
---|
136 | messages: {
|
---|
137 | unexpectedRegExp: "Use a regular expression literal instead of the 'RegExp' constructor.",
|
---|
138 | replaceWithLiteral: "Replace with an equivalent regular expression literal.",
|
---|
139 | replaceWithLiteralAndFlags: "Replace with an equivalent regular expression literal with flags '{{ flags }}'.",
|
---|
140 | replaceWithIntendedLiteralAndFlags: "Replace with a regular expression literal with flags '{{ flags }}'.",
|
---|
141 | unexpectedRedundantRegExp: "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.",
|
---|
142 | unexpectedRedundantRegExpWithFlags: "Use regular expression literal with flags instead of the 'RegExp' constructor."
|
---|
143 | }
|
---|
144 | },
|
---|
145 |
|
---|
146 | create(context) {
|
---|
147 | const [{ disallowRedundantWrapping = false } = {}] = context.options;
|
---|
148 | const sourceCode = context.sourceCode;
|
---|
149 |
|
---|
150 | /**
|
---|
151 | * Determines whether the given identifier node is a reference to a global variable.
|
---|
152 | * @param {ASTNode} node `Identifier` node to check.
|
---|
153 | * @returns {boolean} True if the identifier is a reference to a global variable.
|
---|
154 | */
|
---|
155 | function isGlobalReference(node) {
|
---|
156 | const scope = sourceCode.getScope(node);
|
---|
157 | const variable = findVariable(scope, node);
|
---|
158 |
|
---|
159 | return variable !== null && variable.scope.type === "global" && variable.defs.length === 0;
|
---|
160 | }
|
---|
161 |
|
---|
162 | /**
|
---|
163 | * Determines whether the given node is a String.raw`` tagged template expression
|
---|
164 | * with a static template literal.
|
---|
165 | * @param {ASTNode} node Node to check.
|
---|
166 | * @returns {boolean} True if the node is String.raw`` with a static template.
|
---|
167 | */
|
---|
168 | function isStringRawTaggedStaticTemplateLiteral(node) {
|
---|
169 | return node.type === "TaggedTemplateExpression" &&
|
---|
170 | astUtils.isSpecificMemberAccess(node.tag, "String", "raw") &&
|
---|
171 | isGlobalReference(astUtils.skipChainExpression(node.tag).object) &&
|
---|
172 | astUtils.isStaticTemplateLiteral(node.quasi);
|
---|
173 | }
|
---|
174 |
|
---|
175 | /**
|
---|
176 | * Gets the value of a string
|
---|
177 | * @param {ASTNode} node The node to get the string of.
|
---|
178 | * @returns {string|null} The value of the node.
|
---|
179 | */
|
---|
180 | function getStringValue(node) {
|
---|
181 | if (isStringLiteral(node)) {
|
---|
182 | return node.value;
|
---|
183 | }
|
---|
184 |
|
---|
185 | if (astUtils.isStaticTemplateLiteral(node)) {
|
---|
186 | return node.quasis[0].value.cooked;
|
---|
187 | }
|
---|
188 |
|
---|
189 | if (isStringRawTaggedStaticTemplateLiteral(node)) {
|
---|
190 | return node.quasi.quasis[0].value.raw;
|
---|
191 | }
|
---|
192 |
|
---|
193 | return null;
|
---|
194 | }
|
---|
195 |
|
---|
196 | /**
|
---|
197 | * Determines whether the given node is considered to be a static string by the logic of this rule.
|
---|
198 | * @param {ASTNode} node Node to check.
|
---|
199 | * @returns {boolean} True if the node is a static string.
|
---|
200 | */
|
---|
201 | function isStaticString(node) {
|
---|
202 | return isStringLiteral(node) ||
|
---|
203 | astUtils.isStaticTemplateLiteral(node) ||
|
---|
204 | isStringRawTaggedStaticTemplateLiteral(node);
|
---|
205 | }
|
---|
206 |
|
---|
207 | /**
|
---|
208 | * Determines whether the relevant arguments of the given are all static string literals.
|
---|
209 | * @param {ASTNode} node Node to check.
|
---|
210 | * @returns {boolean} True if all arguments are static strings.
|
---|
211 | */
|
---|
212 | function hasOnlyStaticStringArguments(node) {
|
---|
213 | const args = node.arguments;
|
---|
214 |
|
---|
215 | if ((args.length === 1 || args.length === 2) && args.every(isStaticString)) {
|
---|
216 | return true;
|
---|
217 | }
|
---|
218 |
|
---|
219 | return false;
|
---|
220 | }
|
---|
221 |
|
---|
222 | /**
|
---|
223 | * Determines whether the arguments of the given node indicate that a regex literal is unnecessarily wrapped.
|
---|
224 | * @param {ASTNode} node Node to check.
|
---|
225 | * @returns {boolean} True if the node already contains a regex literal argument.
|
---|
226 | */
|
---|
227 | function isUnnecessarilyWrappedRegexLiteral(node) {
|
---|
228 | const args = node.arguments;
|
---|
229 |
|
---|
230 | if (args.length === 1 && isRegexLiteral(args[0])) {
|
---|
231 | return true;
|
---|
232 | }
|
---|
233 |
|
---|
234 | if (args.length === 2 && isRegexLiteral(args[0]) && isStaticString(args[1])) {
|
---|
235 | return true;
|
---|
236 | }
|
---|
237 |
|
---|
238 | return false;
|
---|
239 | }
|
---|
240 |
|
---|
241 | /**
|
---|
242 | * Returns a ecmaVersion compatible for regexpp.
|
---|
243 | * @param {number} ecmaVersion The ecmaVersion to convert.
|
---|
244 | * @returns {import("@eslint-community/regexpp/ecma-versions").EcmaVersion} The resulting ecmaVersion compatible for regexpp.
|
---|
245 | */
|
---|
246 | function getRegexppEcmaVersion(ecmaVersion) {
|
---|
247 | if (ecmaVersion <= 5) {
|
---|
248 | return 5;
|
---|
249 | }
|
---|
250 | return Math.min(ecmaVersion, REGEXPP_LATEST_ECMA_VERSION);
|
---|
251 | }
|
---|
252 |
|
---|
253 | const regexppEcmaVersion = getRegexppEcmaVersion(context.languageOptions.ecmaVersion);
|
---|
254 |
|
---|
255 | /**
|
---|
256 | * Makes a character escaped or else returns null.
|
---|
257 | * @param {string} character The character to escape.
|
---|
258 | * @returns {string} The resulting escaped character.
|
---|
259 | */
|
---|
260 | function resolveEscapes(character) {
|
---|
261 | switch (character) {
|
---|
262 | case "\n":
|
---|
263 | case "\\\n":
|
---|
264 | return "\\n";
|
---|
265 |
|
---|
266 | case "\r":
|
---|
267 | case "\\\r":
|
---|
268 | return "\\r";
|
---|
269 |
|
---|
270 | case "\t":
|
---|
271 | case "\\\t":
|
---|
272 | return "\\t";
|
---|
273 |
|
---|
274 | case "\v":
|
---|
275 | case "\\\v":
|
---|
276 | return "\\v";
|
---|
277 |
|
---|
278 | case "\f":
|
---|
279 | case "\\\f":
|
---|
280 | return "\\f";
|
---|
281 |
|
---|
282 | case "/":
|
---|
283 | return "\\/";
|
---|
284 |
|
---|
285 | default:
|
---|
286 | return null;
|
---|
287 | }
|
---|
288 | }
|
---|
289 |
|
---|
290 | /**
|
---|
291 | * Checks whether the given regex and flags are valid for the ecma version or not.
|
---|
292 | * @param {string} pattern The regex pattern to check.
|
---|
293 | * @param {string | undefined} flags The regex flags to check.
|
---|
294 | * @returns {boolean} True if the given regex pattern and flags are valid for the ecma version.
|
---|
295 | */
|
---|
296 | function isValidRegexForEcmaVersion(pattern, flags) {
|
---|
297 | const validator = new RegExpValidator({ ecmaVersion: regexppEcmaVersion });
|
---|
298 |
|
---|
299 | try {
|
---|
300 | validator.validatePattern(pattern, 0, pattern.length, {
|
---|
301 | unicode: flags ? flags.includes("u") : false,
|
---|
302 | unicodeSets: flags ? flags.includes("v") : false
|
---|
303 | });
|
---|
304 | if (flags) {
|
---|
305 | validator.validateFlags(flags);
|
---|
306 | }
|
---|
307 | return true;
|
---|
308 | } catch {
|
---|
309 | return false;
|
---|
310 | }
|
---|
311 | }
|
---|
312 |
|
---|
313 | /**
|
---|
314 | * Checks whether two given regex flags contain the same flags or not.
|
---|
315 | * @param {string} flagsA The regex flags.
|
---|
316 | * @param {string} flagsB The regex flags.
|
---|
317 | * @returns {boolean} True if two regex flags contain same flags.
|
---|
318 | */
|
---|
319 | function areFlagsEqual(flagsA, flagsB) {
|
---|
320 | return [...flagsA].sort().join("") === [...flagsB].sort().join("");
|
---|
321 | }
|
---|
322 |
|
---|
323 |
|
---|
324 | /**
|
---|
325 | * Merges two regex flags.
|
---|
326 | * @param {string} flagsA The regex flags.
|
---|
327 | * @param {string} flagsB The regex flags.
|
---|
328 | * @returns {string} The merged regex flags.
|
---|
329 | */
|
---|
330 | function mergeRegexFlags(flagsA, flagsB) {
|
---|
331 | const flagsSet = new Set([
|
---|
332 | ...flagsA,
|
---|
333 | ...flagsB
|
---|
334 | ]);
|
---|
335 |
|
---|
336 | return [...flagsSet].join("");
|
---|
337 | }
|
---|
338 |
|
---|
339 | /**
|
---|
340 | * Checks whether a give node can be fixed to the given regex pattern and flags.
|
---|
341 | * @param {ASTNode} node The node to check.
|
---|
342 | * @param {string} pattern The regex pattern to check.
|
---|
343 | * @param {string} flags The regex flags
|
---|
344 | * @returns {boolean} True if a node can be fixed to the given regex pattern and flags.
|
---|
345 | */
|
---|
346 | function canFixTo(node, pattern, flags) {
|
---|
347 | const tokenBefore = sourceCode.getTokenBefore(node);
|
---|
348 |
|
---|
349 | return sourceCode.getCommentsInside(node).length === 0 &&
|
---|
350 | (!tokenBefore || validPrecedingTokens.has(tokenBefore.value)) &&
|
---|
351 | isValidRegexForEcmaVersion(pattern, flags);
|
---|
352 | }
|
---|
353 |
|
---|
354 | /**
|
---|
355 | * Returns a safe output code considering the before and after tokens.
|
---|
356 | * @param {ASTNode} node The regex node.
|
---|
357 | * @param {string} newRegExpValue The new regex expression value.
|
---|
358 | * @returns {string} The output code.
|
---|
359 | */
|
---|
360 | function getSafeOutput(node, newRegExpValue) {
|
---|
361 | const tokenBefore = sourceCode.getTokenBefore(node);
|
---|
362 | const tokenAfter = sourceCode.getTokenAfter(node);
|
---|
363 |
|
---|
364 | return (tokenBefore && !canTokensBeAdjacent(tokenBefore, newRegExpValue) && tokenBefore.range[1] === node.range[0] ? " " : "") +
|
---|
365 | newRegExpValue +
|
---|
366 | (tokenAfter && !canTokensBeAdjacent(newRegExpValue, tokenAfter) && node.range[1] === tokenAfter.range[0] ? " " : "");
|
---|
367 |
|
---|
368 | }
|
---|
369 |
|
---|
370 | return {
|
---|
371 | Program(node) {
|
---|
372 | const scope = sourceCode.getScope(node);
|
---|
373 | const tracker = new ReferenceTracker(scope);
|
---|
374 | const traceMap = {
|
---|
375 | RegExp: {
|
---|
376 | [CALL]: true,
|
---|
377 | [CONSTRUCT]: true
|
---|
378 | }
|
---|
379 | };
|
---|
380 |
|
---|
381 | for (const { node: refNode } of tracker.iterateGlobalReferences(traceMap)) {
|
---|
382 | if (disallowRedundantWrapping && isUnnecessarilyWrappedRegexLiteral(refNode)) {
|
---|
383 | const regexNode = refNode.arguments[0];
|
---|
384 |
|
---|
385 | if (refNode.arguments.length === 2) {
|
---|
386 | const suggests = [];
|
---|
387 |
|
---|
388 | const argFlags = getStringValue(refNode.arguments[1]) || "";
|
---|
389 |
|
---|
390 | if (canFixTo(refNode, regexNode.regex.pattern, argFlags)) {
|
---|
391 | suggests.push({
|
---|
392 | messageId: "replaceWithLiteralAndFlags",
|
---|
393 | pattern: regexNode.regex.pattern,
|
---|
394 | flags: argFlags
|
---|
395 | });
|
---|
396 | }
|
---|
397 |
|
---|
398 | const literalFlags = regexNode.regex.flags || "";
|
---|
399 | const mergedFlags = mergeRegexFlags(literalFlags, argFlags);
|
---|
400 |
|
---|
401 | if (
|
---|
402 | !areFlagsEqual(mergedFlags, argFlags) &&
|
---|
403 | canFixTo(refNode, regexNode.regex.pattern, mergedFlags)
|
---|
404 | ) {
|
---|
405 | suggests.push({
|
---|
406 | messageId: "replaceWithIntendedLiteralAndFlags",
|
---|
407 | pattern: regexNode.regex.pattern,
|
---|
408 | flags: mergedFlags
|
---|
409 | });
|
---|
410 | }
|
---|
411 |
|
---|
412 | context.report({
|
---|
413 | node: refNode,
|
---|
414 | messageId: "unexpectedRedundantRegExpWithFlags",
|
---|
415 | suggest: suggests.map(({ flags, pattern, messageId }) => ({
|
---|
416 | messageId,
|
---|
417 | data: {
|
---|
418 | flags
|
---|
419 | },
|
---|
420 | fix(fixer) {
|
---|
421 | return fixer.replaceText(refNode, getSafeOutput(refNode, `/${pattern}/${flags}`));
|
---|
422 | }
|
---|
423 | }))
|
---|
424 | });
|
---|
425 | } else {
|
---|
426 | const outputs = [];
|
---|
427 |
|
---|
428 | if (canFixTo(refNode, regexNode.regex.pattern, regexNode.regex.flags)) {
|
---|
429 | outputs.push(sourceCode.getText(regexNode));
|
---|
430 | }
|
---|
431 |
|
---|
432 |
|
---|
433 | context.report({
|
---|
434 | node: refNode,
|
---|
435 | messageId: "unexpectedRedundantRegExp",
|
---|
436 | suggest: outputs.map(output => ({
|
---|
437 | messageId: "replaceWithLiteral",
|
---|
438 | fix(fixer) {
|
---|
439 | return fixer.replaceText(
|
---|
440 | refNode,
|
---|
441 | getSafeOutput(refNode, output)
|
---|
442 | );
|
---|
443 | }
|
---|
444 | }))
|
---|
445 | });
|
---|
446 | }
|
---|
447 | } else if (hasOnlyStaticStringArguments(refNode)) {
|
---|
448 | let regexContent = getStringValue(refNode.arguments[0]);
|
---|
449 | let noFix = false;
|
---|
450 | let flags;
|
---|
451 |
|
---|
452 | if (refNode.arguments[1]) {
|
---|
453 | flags = getStringValue(refNode.arguments[1]);
|
---|
454 | }
|
---|
455 |
|
---|
456 | if (!canFixTo(refNode, regexContent, flags)) {
|
---|
457 | noFix = true;
|
---|
458 | }
|
---|
459 |
|
---|
460 | if (!/^[-a-zA-Z0-9\\[\](){} \t\r\n\v\f!@#$%^&*+^_=/~`.><?,'"|:;]*$/u.test(regexContent)) {
|
---|
461 | noFix = true;
|
---|
462 | }
|
---|
463 |
|
---|
464 | if (regexContent && !noFix) {
|
---|
465 | let charIncrease = 0;
|
---|
466 |
|
---|
467 | const ast = new RegExpParser({ ecmaVersion: regexppEcmaVersion }).parsePattern(regexContent, 0, regexContent.length, {
|
---|
468 | unicode: flags ? flags.includes("u") : false,
|
---|
469 | unicodeSets: flags ? flags.includes("v") : false
|
---|
470 | });
|
---|
471 |
|
---|
472 | visitRegExpAST(ast, {
|
---|
473 | onCharacterEnter(characterNode) {
|
---|
474 | const escaped = resolveEscapes(characterNode.raw);
|
---|
475 |
|
---|
476 | if (escaped) {
|
---|
477 | regexContent =
|
---|
478 | regexContent.slice(0, characterNode.start + charIncrease) +
|
---|
479 | escaped +
|
---|
480 | regexContent.slice(characterNode.end + charIncrease);
|
---|
481 |
|
---|
482 | if (characterNode.raw.length === 1) {
|
---|
483 | charIncrease += 1;
|
---|
484 | }
|
---|
485 | }
|
---|
486 | }
|
---|
487 | });
|
---|
488 | }
|
---|
489 |
|
---|
490 | const newRegExpValue = `/${regexContent || "(?:)"}/${flags || ""}`;
|
---|
491 |
|
---|
492 | context.report({
|
---|
493 | node: refNode,
|
---|
494 | messageId: "unexpectedRegExp",
|
---|
495 | suggest: noFix ? [] : [{
|
---|
496 | messageId: "replaceWithLiteral",
|
---|
497 | fix(fixer) {
|
---|
498 | return fixer.replaceText(refNode, getSafeOutput(refNode, newRegExpValue));
|
---|
499 | }
|
---|
500 | }]
|
---|
501 | });
|
---|
502 | }
|
---|
503 | }
|
---|
504 | }
|
---|
505 | };
|
---|
506 | }
|
---|
507 | };
|
---|