• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * @fileoverview Rule to enforce the use of `u` flag on RegExp.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const {
13    CALL,
14    CONSTRUCT,
15    ReferenceTracker,
16    getStringIfConstant
17} = require("eslint-utils");
18
19//------------------------------------------------------------------------------
20// Rule Definition
21//------------------------------------------------------------------------------
22
23module.exports = {
24    meta: {
25        type: "suggestion",
26
27        docs: {
28            description: "enforce the use of `u` flag on RegExp",
29            category: "Best Practices",
30            recommended: false,
31            url: "https://eslint.org/docs/rules/require-unicode-regexp"
32        },
33
34        messages: {
35            requireUFlag: "Use the 'u' flag."
36        },
37
38        schema: []
39    },
40
41    create(context) {
42        return {
43            "Literal[regex]"(node) {
44                const flags = node.regex.flags || "";
45
46                if (!flags.includes("u")) {
47                    context.report({ node, messageId: "requireUFlag" });
48                }
49            },
50
51            Program() {
52                const scope = context.getScope();
53                const tracker = new ReferenceTracker(scope);
54                const trackMap = {
55                    RegExp: { [CALL]: true, [CONSTRUCT]: true }
56                };
57
58                for (const { node } of tracker.iterateGlobalReferences(trackMap)) {
59                    const flagsNode = node.arguments[1];
60                    const flags = getStringIfConstant(flagsNode, scope);
61
62                    if (!flagsNode || (typeof flags === "string" && !flags.includes("u"))) {
63                        context.report({ node, messageId: "requireUFlag" });
64                    }
65                }
66            }
67        };
68    }
69};
70