utils.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 {
  7. CALL,
  8. CONSTRUCT,
  9. PatternMatcher,
  10. ReferenceTracker,
  11. getStringIfConstant,
  12. } = require("eslint-utils")
  13. module.exports = {
  14. /**
  15. * Define generator to search pattern.
  16. * The iterator generated by the generator returns the start and end index of the match.
  17. * @param {RegExp} pattern Base pattern
  18. * @returns {function(string):IterableIterator<RegExpExecArray>} generator
  19. */
  20. definePatternSearchGenerator(pattern) {
  21. const matcher = new PatternMatcher(pattern)
  22. return matcher.execAll.bind(matcher)
  23. },
  24. /**
  25. * Check whether a given token is a comma token or not.
  26. * @param {Token} token The token to check.
  27. * @returns {boolean} `true` if the token is a comma token.
  28. */
  29. isCommaToken(token) {
  30. return (
  31. token != null && token.type === "Punctuator" && token.value === ","
  32. )
  33. },
  34. /**
  35. * Iterate the calls of the `RegExp` global variable.
  36. * @param {Scope} globalScope The global scope object.
  37. * @returns {IterableIterator<{node:Node,pattern:(string|null),flags:(string|null)}>} The iterator of `CallExpression` or `NewExpression` for `RegExp`.
  38. */
  39. *getRegExpCalls(globalScope) {
  40. const tracker = new ReferenceTracker(globalScope)
  41. for (const { node } of tracker.iterateGlobalReferences({
  42. RegExp: { [CALL]: true, [CONSTRUCT]: true },
  43. })) {
  44. const [patternNode, flagsNode] = node.arguments
  45. yield {
  46. node,
  47. pattern: getStringIfConstant(patternNode, globalScope),
  48. flags: getStringIfConstant(flagsNode, globalScope),
  49. }
  50. }
  51. },
  52. }