summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/lib/rules/prefer-regex-literals.js
blob: 39e29506421c2b0ca67b6eb75b55fec1a91b2cdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/**
 * @fileoverview Rule to disallow use of the `RegExp` constructor in favor of regular expression literals
 * @author Milos Djermanovic
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");
const { CALL, CONSTRUCT, ReferenceTracker, findVariable } = require("@eslint-community/eslint-utils");
const { RegExpValidator, visitRegExpAST, RegExpParser } = require("@eslint-community/regexpp");
const { canTokensBeAdjacent } = require("./utils/ast-utils");
const { REGEXPP_LATEST_ECMA_VERSION } = require("./utils/regular-expressions");

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

/**
 * Determines whether the given node is a string literal.
 * @param {ASTNode} node Node to check.
 * @returns {boolean} True if the node is a string literal.
 */
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.
 * @returns {boolean} True if the node is a template literal without expressions.
 */
function isStaticTemplateLiteral(node) {
    return node.type === "TemplateLiteral" && node.expressions.length === 0;
}

const validPrecedingTokens = new Set([
    "(",
    ";",
    "[",
    ",",
    "=",
    "+",
    "*",
    "-",
    "?",
    "~",
    "%",
    "**",
    "!",
    "typeof",
    "instanceof",
    "&&",
    "||",
    "??",
    "return",
    "...",
    "delete",
    "void",
    "in",
    "<",
    ">",
    "<=",
    ">=",
    "==",
    "===",
    "!=",
    "!==",
    "<<",
    ">>",
    ">>>",
    "&",
    "|",
    "^",
    ":",
    "{",
    "=>",
    "*=",
    "<<=",
    ">>=",
    ">>>=",
    "^=",
    "|=",
    "&=",
    "??=",
    "||=",
    "&&=",
    "**=",
    "+=",
    "-=",
    "/=",
    "%=",
    "/",
    "do",
    "break",
    "continue",
    "debugger",
    "case",
    "throw"
]);


//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "Disallow use of the `RegExp` constructor in favor of regular expression literals",
            recommended: false,
            url: "https://eslint.org/docs/latest/rules/prefer-regex-literals"
        },

        hasSuggestions: true,

        schema: [
            {
                type: "object",
                properties: {
                    disallowRedundantWrapping: {
                        type: "boolean",
                        default: false
                    }
                },
                additionalProperties: false
            }
        ],

        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 '{{ flags }}'.",
            replaceWithIntendedLiteralAndFlags: "Replace with a regular expression literal with flags '{{ flags }}'.",
            unexpectedRedundantRegExp: "Regular expression literal is unnecessarily wrapped within a 'RegExp' constructor.",
            unexpectedRedundantRegExpWithFlags: "Use regular expression literal with flags instead of the 'RegExp' constructor."
        }
    },

    create(context) {
        const [{ disallowRedundantWrapping = false } = {}] = context.options;
        const sourceCode = context.sourceCode;

        /**
         * Determines whether the given identifier node is a reference to a global variable.
         * @param {ASTNode} node `Identifier` node to check.
         * @returns {boolean} True if the identifier is a reference to a global variable.
         */
        function isGlobalReference(node) {
            const scope = sourceCode.getScope(node);
            const variable = findVariable(scope, node);

            return variable !== null && variable.scope.type === "global" && variable.defs.length === 0;
        }

        /**
         * Determines whether the given node is a String.raw`` tagged template expression
         * with a static template literal.
         * @param {ASTNode} node Node to check.
         * @returns {boolean} True if the node is String.raw`` with a static template.
         */
        function isStringRawTaggedStaticTemplateLiteral(node) {
            return node.type === "TaggedTemplateExpression" &&
                astUtils.isSpecificMemberAccess(node.tag, "String", "raw") &&
                isGlobalReference(astUtils.skipChainExpression(node.tag).object) &&
                isStaticTemplateLiteral(node.quasi);
        }

        /**
         * Gets the value of a string
         * @param {ASTNode} node The node to get the string of.
         * @returns {string|null} The value of the node.
         */
        function getStringValue(node) {
            if (isStringLiteral(node)) {
                return node.value;
            }

            if (isStaticTemplateLiteral(node)) {
                return node.quasis[0].value.cooked;
            }

            if (isStringRawTaggedStaticTemplateLiteral(node)) {
                return node.quasi.quasis[0].value.raw;
            }

            return null;
        }

        /**
         * Determines whether the given node is considered to be a static string by the logic of this rule.
         * @param {ASTNode} node Node to check.
         * @returns {boolean} True if the node is a static string.
         */
        function isStaticString(node) {
            return isStringLiteral(node) ||
                isStaticTemplateLiteral(node) ||
                isStringRawTaggedStaticTemplateLiteral(node);
        }

        /**
         * Determines whether the relevant arguments of the given are all static string literals.
         * @param {ASTNode} node Node to check.
         * @returns {boolean} True if all arguments are static strings.
         */
        function hasOnlyStaticStringArguments(node) {
            const args = node.arguments;

            if ((args.length === 1 || args.length === 2) && args.every(isStaticString)) {
                return true;
            }

            return false;
        }

        /**
         * Determines whether the arguments of the given node indicate that a regex literal is unnecessarily wrapped.
         * @param {ASTNode} node Node to check.
         * @returns {boolean} True if the node already contains a regex literal argument.
         */
        function isUnnecessarilyWrappedRegexLiteral(node) {
            const args = node.arguments;

            if (args.length === 1 && isRegexLiteral(args[0])) {
                return true;
            }

            if (args.length === 2 && isRegexLiteral(args[0]) && isStaticString(args[1])) {
                return true;
            }

            return false;
        }

        /**
         * Returns a ecmaVersion compatible for regexpp.
         * @param {number} ecmaVersion The ecmaVersion to convert.
         * @returns {import("regexpp/ecma-versions").EcmaVersion} The resulting ecmaVersion compatible for regexpp.
         */
        function getRegexppEcmaVersion(ecmaVersion) {
            if (ecmaVersion <= 5) {
                return 5;
            }
            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.
         * @returns {string} The resulting escaped character.
         */
        function resolveEscapes(character) {
            switch (character) {
                case "\n":
                case "\\\n":
                    return "\\n";

                case "\r":
                case "\\\r":
                    return "\\r";

                case "\t":
                case "\\\t":
                    return "\\t";

                case "\v":
                case "\\\v":
                    return "\\v";

                case "\f":
                case "\\\f":
                    return "\\f";

                case "/":
                    return "\\/";

                default:
                    return null;
            }
        }

        /**
         * 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("");
        }

        /**
         * Checks whether a give node can be fixed to the given regex pattern and flags.
         * @param {ASTNode} node The node to check.
         * @param {string} pattern The regex pattern to check.
         * @param {string} flags The regex flags
         * @returns {boolean} True if a node can be fixed to the given regex pattern and flags.
         */
        function canFixTo(node, pattern, flags) {
            const tokenBefore = sourceCode.getTokenBefore(node);

            return sourceCode.getCommentsInside(node).length === 0 &&
                (!tokenBefore || validPrecedingTokens.has(tokenBefore.value)) &&
                isValidRegexForEcmaVersion(pattern, flags);
        }

        /**
         * Returns a safe output code considering the before and after tokens.
         * @param {ASTNode} node The regex node.
         * @param {string} newRegExpValue The new regex expression value.
         * @returns {string} The output code.
         */
        function getSafeOutput(node, newRegExpValue) {
            const tokenBefore = sourceCode.getTokenBefore(node);
            const tokenAfter = sourceCode.getTokenAfter(node);

            return (tokenBefore && !canTokensBeAdjacent(tokenBefore, newRegExpValue) && tokenBefore.range[1] === node.range[0] ? " " : "") +
                newRegExpValue +
            (tokenAfter && !canTokensBeAdjacent(newRegExpValue, tokenAfter) && node.range[1] === tokenAfter.range[0] ? " " : "");

        }

        return {
            Program(node) {
                const scope = sourceCode.getScope(node);
                const tracker = new ReferenceTracker(scope);
                const traceMap = {
                    RegExp: {
                        [CALL]: true,
                        [CONSTRUCT]: true
                    }
                };

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

                        if (refNode.arguments.length === 2) {
                            const suggests = [];

                            const argFlags = getStringValue(refNode.arguments[1]) || "";

                            if (canFixTo(refNode, regexNode.regex.pattern, argFlags)) {
                                suggests.push({
                                    messageId: "replaceWithLiteralAndFlags",
                                    pattern: regexNode.regex.pattern,
                                    flags: argFlags
                                });
                            }

                            const literalFlags = regexNode.regex.flags || "";
                            const mergedFlags = mergeRegexFlags(literalFlags, argFlags);

                            if (
                                !areFlagsEqual(mergedFlags, argFlags) &&
                                canFixTo(refNode, regexNode.regex.pattern, mergedFlags)
                            ) {
                                suggests.push({
                                    messageId: "replaceWithIntendedLiteralAndFlags",
                                    pattern: regexNode.regex.pattern,
                                    flags: mergedFlags
                                });
                            }

                            context.report({
                                node: refNode,
                                messageId: "unexpectedRedundantRegExpWithFlags",
                                suggest: suggests.map(({ flags, pattern, messageId }) => ({
                                    messageId,
                                    data: {
                                        flags
                                    },
                                    fix(fixer) {
                                        return fixer.replaceText(refNode, getSafeOutput(refNode, `/${pattern}/${flags}`));
                                    }
                                }))
                            });
                        } else {
                            const outputs = [];

                            if (canFixTo(refNode, regexNode.regex.pattern, regexNode.regex.flags)) {
                                outputs.push(sourceCode.getText(regexNode));
                            }


                            context.report({
                                node: refNode,
                                messageId: "unexpectedRedundantRegExp",
                                suggest: outputs.map(output => ({
                                    messageId: "replaceWithLiteral",
                                    fix(fixer) {
                                        return fixer.replaceText(
                                            refNode,
                                            getSafeOutput(refNode, output)
                                        );
                                    }
                                }))
                            });
                        }
                    } else if (hasOnlyStaticStringArguments(refNode)) {
                        let regexContent = getStringValue(refNode.arguments[0]);
                        let noFix = false;
                        let flags;

                        if (refNode.arguments[1]) {
                            flags = getStringValue(refNode.arguments[1]);
                        }

                        if (!canFixTo(refNode, regexContent, flags)) {
                            noFix = true;
                        }

                        if (!/^[-a-zA-Z0-9\\[\](){} \t\r\n\v\f!@#$%^&*+^_=/~`.><?,'"|:;]*$/u.test(regexContent)) {
                            noFix = true;
                        }

                        if (regexContent && !noFix) {
                            let charIncrease = 0;

                            const ast = new RegExpParser({ ecmaVersion: regexppEcmaVersion }).parsePattern(regexContent, 0, regexContent.length, flags ? flags.includes("u") : false);

                            visitRegExpAST(ast, {
                                onCharacterEnter(characterNode) {
                                    const escaped = resolveEscapes(characterNode.raw);

                                    if (escaped) {
                                        regexContent =
                                            regexContent.slice(0, characterNode.start + charIncrease) +
                                            escaped +
                                            regexContent.slice(characterNode.end + charIncrease);

                                        if (characterNode.raw.length === 1) {
                                            charIncrease += 1;
                                        }
                                    }
                                }
                            });
                        }

                        const newRegExpValue = `/${regexContent || "(?:)"}/${flags || ""}`;

                        context.report({
                            node: refNode,
                            messageId: "unexpectedRegExp",
                            suggest: noFix ? [] : [{
                                messageId: "replaceWithLiteral",
                                fix(fixer) {
                                    return fixer.replaceText(refNode, getSafeOutput(refNode, newRegExpValue));
                                }
                            }]
                        });
                    }
                }
            }
        };
    }
};