no-regexp-unicode-property-escapes.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const { RegExpValidator } = require("regexpp")
  7. const { getRegExpCalls } = require("../utils")
  8. /**
  9. * Verify a given regular expression.
  10. * @param {RuleContext} context The rule context to report.
  11. * @param {Node} node The AST node to report.
  12. * @param {string} pattern The pattern part of a RegExp.
  13. * @param {string} flags The flags part of a RegExp.
  14. * @returns {void}
  15. */
  16. function verify(context, node, pattern, flags) {
  17. try {
  18. let found = false
  19. new RegExpValidator({
  20. onUnicodePropertyCharacterSet() {
  21. found = true
  22. },
  23. }).validatePattern(pattern, 0, pattern.length, flags.includes("u"))
  24. if (found) {
  25. context.report({ node, messageId: "forbidden" })
  26. }
  27. } catch (error) {
  28. //istanbul ignore else
  29. if (error.message.startsWith("Invalid regular expression:")) {
  30. return
  31. }
  32. //istanbul ignore next
  33. throw error
  34. }
  35. }
  36. module.exports = {
  37. meta: {
  38. docs: {
  39. description: "disallow RegExp Unicode property escape sequences.",
  40. category: "ES2018",
  41. recommended: false,
  42. url:
  43. "http://mysticatea.github.io/eslint-plugin-es/rules/no-regexp-unicode-property-escapes.html",
  44. },
  45. fixable: null,
  46. schema: [],
  47. messages: {
  48. forbidden:
  49. "ES2018 RegExp Unicode property escape sequences are forbidden.",
  50. },
  51. },
  52. create(context) {
  53. return {
  54. "Literal[regex]"(node) {
  55. const { pattern, flags } = node.regex
  56. verify(context, node, pattern || "", flags || "")
  57. },
  58. "Program:exit"() {
  59. const scope = context.getScope()
  60. for (const { node, pattern, flags } of getRegExpCalls(scope)) {
  61. verify(context, node, pattern || "", flags || "")
  62. }
  63. },
  64. }
  65. },
  66. }