no-class-assign.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * @fileoverview A rule to disallow modifying variables of class declarations
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. const astUtils = require("./utils/ast-utils");
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../shared/types').Rule} */
  11. module.exports = {
  12. meta: {
  13. type: "problem",
  14. docs: {
  15. description: "Disallow reassigning class members",
  16. recommended: true,
  17. url: "https://eslint.org/docs/rules/no-class-assign"
  18. },
  19. schema: [],
  20. messages: {
  21. class: "'{{name}}' is a class."
  22. }
  23. },
  24. create(context) {
  25. /**
  26. * Finds and reports references that are non initializer and writable.
  27. * @param {Variable} variable A variable to check.
  28. * @returns {void}
  29. */
  30. function checkVariable(variable) {
  31. astUtils.getModifyingReferences(variable.references).forEach(reference => {
  32. context.report({ node: reference.identifier, messageId: "class", data: { name: reference.identifier.name } });
  33. });
  34. }
  35. /**
  36. * Finds and reports references that are non initializer and writable.
  37. * @param {ASTNode} node A ClassDeclaration/ClassExpression node to check.
  38. * @returns {void}
  39. */
  40. function checkForClass(node) {
  41. context.getDeclaredVariables(node).forEach(checkVariable);
  42. }
  43. return {
  44. ClassDeclaration: checkForClass,
  45. ClassExpression: checkForClass
  46. };
  47. }
  48. };