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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. messages: {
  47. forbidden:
  48. "ES2018 RegExp Unicode property escape sequences are forbidden.",
  49. },
  50. schema: [],
  51. type: "problem",
  52. },
  53. create(context) {
  54. return {
  55. "Literal[regex]"(node) {
  56. const { pattern, flags } = node.regex
  57. verify(context, node, pattern || "", flags || "")
  58. },
  59. "Program:exit"() {
  60. const scope = context.getScope()
  61. for (const { node, pattern, flags } of getRegExpCalls(scope)) {
  62. verify(context, node, pattern || "", flags || "")
  63. }
  64. },
  65. }
  66. },
  67. }