You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

66 lines
1.9 KiB

  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. module.exports = {
  19. meta: {
  20. docs: {
  21. description: "enforce the use of `u` flag on RegExp",
  22. category: "Best Practices",
  23. recommended: false,
  24. url: "https://eslint.org/docs/rules/require-unicode-regexp"
  25. },
  26. messages: {
  27. requireUFlag: "Use the 'u' flag."
  28. },
  29. schema: []
  30. },
  31. create(context) {
  32. return {
  33. "Literal[regex]"(node) {
  34. const flags = node.regex.flags || "";
  35. if (!flags.includes("u")) {
  36. context.report({ node, messageId: "requireUFlag" });
  37. }
  38. },
  39. Program() {
  40. const scope = context.getScope();
  41. const tracker = new ReferenceTracker(scope);
  42. const trackMap = {
  43. RegExp: { [CALL]: true, [CONSTRUCT]: true }
  44. };
  45. for (const { node } of tracker.iterateGlobalReferences(trackMap)) {
  46. const flagsNode = node.arguments[1];
  47. const flags = getStringIfConstant(flagsNode, scope);
  48. if (!flagsNode || (typeof flags === "string" && !flags.includes("u"))) {
  49. context.report({ node, messageId: "requireUFlag" });
  50. }
  51. }
  52. }
  53. };
  54. }
  55. };