no-regexp-named-capture-groups.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. onCapturingGroupEnter(_start, name) {
  21. if (name) {
  22. found = true
  23. }
  24. },
  25. onBackreference(_start, _end, ref) {
  26. if (typeof ref === "string") {
  27. found = true
  28. }
  29. },
  30. }).validatePattern(pattern, 0, pattern.length, flags.includes("u"))
  31. if (found) {
  32. context.report({ node, messageId: "forbidden" })
  33. }
  34. } catch (error) {
  35. //istanbul ignore else
  36. if (error.message.startsWith("Invalid regular expression:")) {
  37. return
  38. }
  39. //istanbul ignore next
  40. throw error
  41. }
  42. }
  43. module.exports = {
  44. meta: {
  45. docs: {
  46. description: "disallow RegExp named capture groups.",
  47. category: "ES2018",
  48. recommended: false,
  49. url:
  50. "http://mysticatea.github.io/eslint-plugin-es/rules/no-regexp-named-capture-groups.html",
  51. },
  52. fixable: null,
  53. messages: {
  54. forbidden: "ES2018 RegExp named capture groups are forbidden.",
  55. },
  56. schema: [],
  57. type: "problem",
  58. },
  59. create(context) {
  60. return {
  61. "Literal[regex]"(node) {
  62. const { pattern, flags } = node.regex
  63. verify(context, node, pattern || "", flags || "")
  64. },
  65. "Program:exit"() {
  66. const scope = context.getScope()
  67. for (const { node, pattern, flags } of getRegExpCalls(scope)) {
  68. verify(context, node, pattern || "", flags || "")
  69. }
  70. },
  71. }
  72. },
  73. }