UNPKG

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