no-native-reassign.js 2.8 KB

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