check-prefer-global.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * @author Toru Nagashima
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. const { ReferenceTracker } = require("eslint-utils")
  7. /**
  8. * Verifier for `prefer-global/*` rules.
  9. */
  10. class Verifier {
  11. /**
  12. * Initialize this instance.
  13. * @param {RuleContext} context The rule context to report.
  14. * @param {{modules:object,globals:object}} trackMap The track map.
  15. */
  16. constructor(context, trackMap) {
  17. this.context = context
  18. this.trackMap = trackMap
  19. this.verify =
  20. context.options[0] === "never"
  21. ? this.verifyToPreferModules
  22. : this.verifyToPreferGlobals
  23. }
  24. /**
  25. * Verify the code to suggest the use of globals.
  26. * @returns {void}
  27. */
  28. verifyToPreferGlobals() {
  29. const { context, trackMap } = this
  30. const tracker = new ReferenceTracker(context.getScope(), {
  31. mode: "legacy",
  32. })
  33. for (const { node } of [
  34. ...tracker.iterateCjsReferences(trackMap.modules),
  35. ...tracker.iterateEsmReferences(trackMap.modules),
  36. ]) {
  37. context.report({ node, messageId: "preferGlobal" })
  38. }
  39. }
  40. /**
  41. * Verify the code to suggest the use of modules.
  42. * @returns {void}
  43. */
  44. verifyToPreferModules() {
  45. const { context, trackMap } = this
  46. const tracker = new ReferenceTracker(context.getScope())
  47. for (const { node } of tracker.iterateGlobalReferences(
  48. trackMap.globals
  49. )) {
  50. context.report({ node, messageId: "preferModule" })
  51. }
  52. }
  53. }
  54. module.exports = function checkForPreferGlobal(context, trackMap) {
  55. new Verifier(context, trackMap).verify()
  56. }