require-unicode-regexp.js 1.9 KB

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