no-const-assign.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @fileoverview A rule to disallow modifying variables that are declared using `const`
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const CONSTANT_BINDINGS = new Set(["const", "using", "await using"]);
  14. //------------------------------------------------------------------------------
  15. // Rule Definition
  16. //------------------------------------------------------------------------------
  17. /** @type {import('../types').Rule.RuleModule} */
  18. module.exports = {
  19. meta: {
  20. type: "problem",
  21. docs: {
  22. description:
  23. "Disallow reassigning `const`, `using`, and `await using` variables",
  24. recommended: true,
  25. url: "https://eslint.org/docs/latest/rules/no-const-assign",
  26. },
  27. schema: [],
  28. messages: {
  29. const: "'{{name}}' is constant.",
  30. },
  31. },
  32. create(context) {
  33. const sourceCode = context.sourceCode;
  34. /**
  35. * Finds and reports references that are non initializer and writable.
  36. * @param {Variable} variable A variable to check.
  37. * @returns {void}
  38. */
  39. function checkVariable(variable) {
  40. astUtils
  41. .getModifyingReferences(variable.references)
  42. .forEach(reference => {
  43. context.report({
  44. node: reference.identifier,
  45. messageId: "const",
  46. data: { name: reference.identifier.name },
  47. });
  48. });
  49. }
  50. return {
  51. VariableDeclaration(node) {
  52. if (CONSTANT_BINDINGS.has(node.kind)) {
  53. sourceCode
  54. .getDeclaredVariables(node)
  55. .forEach(checkVariable);
  56. }
  57. },
  58. };
  59. },
  60. };