Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 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 | |
| 12 | const { |
| 13 | CALL, |
| 14 | CONSTRUCT, |
| 15 | ReferenceTracker, |
| 16 | getStringIfConstant |
| 17 | } = require("eslint-utils"); |
| 18 | |
| 19 | //------------------------------------------------------------------------------ |
| 20 | // Rule Definition |
| 21 | //------------------------------------------------------------------------------ |
| 22 | |
| 23 | module.exports = { |
| 24 | meta: { |
| 25 | type: "suggestion", |
| 26 | |
| 27 | docs: { |
| 28 | description: "enforce the use of `u` flag on RegExp", |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 29 | recommended: false, |
| 30 | url: "https://eslint.org/docs/rules/require-unicode-regexp" |
| 31 | }, |
| 32 | |
| 33 | messages: { |
| 34 | requireUFlag: "Use the 'u' flag." |
| 35 | }, |
| 36 | |
| 37 | schema: [] |
| 38 | }, |
| 39 | |
| 40 | create(context) { |
| 41 | return { |
| 42 | "Literal[regex]"(node) { |
| 43 | const flags = node.regex.flags || ""; |
| 44 | |
| 45 | if (!flags.includes("u")) { |
| 46 | context.report({ node, messageId: "requireUFlag" }); |
| 47 | } |
| 48 | }, |
| 49 | |
| 50 | Program() { |
| 51 | const scope = context.getScope(); |
| 52 | const tracker = new ReferenceTracker(scope); |
| 53 | const trackMap = { |
| 54 | RegExp: { [CALL]: true, [CONSTRUCT]: true } |
| 55 | }; |
| 56 | |
| 57 | for (const { node } of tracker.iterateGlobalReferences(trackMap)) { |
| 58 | const flagsNode = node.arguments[1]; |
| 59 | const flags = getStringIfConstant(flagsNode, scope); |
| 60 | |
| 61 | if (!flagsNode || (typeof flags === "string" && !flags.includes("u"))) { |
| 62 | context.report({ node, messageId: "requireUFlag" }); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | }; |
| 67 | } |
| 68 | }; |