no-native-reassign.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * @fileoverview Rule to disallow assignments to native objects or read-only global variables
  3. * @author Ilya Volodin
  4. * @deprecated in ESLint v3.3.0
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Rule Definition
  9. //------------------------------------------------------------------------------
  10. /** @type {import('../shared/types').Rule} */
  11. module.exports = {
  12. meta: {
  13. type: "suggestion",
  14. docs: {
  15. description: "Disallow assignments to native objects or read-only global variables",
  16. recommended: false,
  17. url: "https://eslint.org/docs/rules/no-native-reassign"
  18. },
  19. deprecated: true,
  20. replacedBy: ["no-global-assign"],
  21. schema: [
  22. {
  23. type: "object",
  24. properties: {
  25. exceptions: {
  26. type: "array",
  27. items: { type: "string" },
  28. uniqueItems: true
  29. }
  30. },
  31. additionalProperties: false
  32. }
  33. ],
  34. messages: {
  35. nativeReassign: "Read-only global '{{name}}' should not be modified."
  36. }
  37. },
  38. create(context) {
  39. const config = context.options[0];
  40. const exceptions = (config && config.exceptions) || [];
  41. /**
  42. * Reports write references.
  43. * @param {Reference} reference A reference to check.
  44. * @param {int} index The index of the reference in the references.
  45. * @param {Reference[]} references The array that the reference belongs to.
  46. * @returns {void}
  47. */
  48. function checkReference(reference, index, references) {
  49. const identifier = reference.identifier;
  50. if (reference.init === false &&
  51. reference.isWrite() &&
  52. /*
  53. * Destructuring assignments can have multiple default value,
  54. * so possibly there are multiple writeable references for the same identifier.
  55. */
  56. (index === 0 || references[index - 1].identifier !== identifier)
  57. ) {
  58. context.report({
  59. node: identifier,
  60. messageId: "nativeReassign",
  61. data: identifier
  62. });
  63. }
  64. }
  65. /**
  66. * Reports write references if a given variable is read-only builtin.
  67. * @param {Variable} variable A variable to check.
  68. * @returns {void}
  69. */
  70. function checkVariable(variable) {
  71. if (variable.writeable === false && !exceptions.includes(variable.name)) {
  72. variable.references.forEach(checkReference);
  73. }
  74. }
  75. return {
  76. Program() {
  77. const globalScope = context.getScope();
  78. globalScope.variables.forEach(checkVariable);
  79. }
  80. };
  81. }
  82. };