summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/lib/rules/no-param-reassign.js
blob: d65eb34762aaf207eb9858dea0830d5e18fdd323 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
 * @fileoverview Disallow reassignment of function parameters.
 * @author Nat Burns
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const stopNodePattern = /(?:Statement|Declaration|Function(?:Expression)?|Program)$/u;

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow reassigning `function` parameters",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-param-reassign"
        },

        schema: [
            {
                oneOf: [
                    {
                        type: "object",
                        properties: {
                            props: {
                                enum: [false]
                            }
                        },
                        additionalProperties: false
                    },
                    {
                        type: "object",
                        properties: {
                            props: {
                                enum: [true]
                            },
                            ignorePropertyModificationsFor: {
                                type: "array",
                                items: {
                                    type: "string"
                                },
                                uniqueItems: true
                            },
                            ignorePropertyModificationsForRegex: {
                                type: "array",
                                items: {
                                    type: "string"
                                },
                                uniqueItems: true
                            }
                        },
                        additionalProperties: false
                    }
                ]
            }
        ]
    },

    create(context) {
        const props = context.options[0] && context.options[0].props;
        const ignoredPropertyAssignmentsFor = context.options[0] && context.options[0].ignorePropertyModificationsFor || [];
        const ignoredPropertyAssignmentsForRegex = context.options[0] && context.options[0].ignorePropertyModificationsForRegex || [];

        /**
         * Checks whether or not the reference modifies properties of its variable.
         * @param {Reference} reference A reference to check.
         * @returns {boolean} Whether or not the reference modifies properties of its variable.
         */
        function isModifyingProp(reference) {
            let node = reference.identifier;
            let parent = node.parent;

            while (parent && (!stopNodePattern.test(parent.type) ||
                    parent.type === "ForInStatement" || parent.type === "ForOfStatement")) {
                switch (parent.type) {

                    // e.g. foo.a = 0;
                    case "AssignmentExpression":
                        return parent.left === node;

                    // e.g. ++foo.a;
                    case "UpdateExpression":
                        return true;

                    // e.g. delete foo.a;
                    case "UnaryExpression":
                        if (parent.operator === "delete") {
                            return true;
                        }
                        break;

                    // e.g. for (foo.a in b) {}
                    case "ForInStatement":
                    case "ForOfStatement":
                        if (parent.left === node) {
                            return true;
                        }

                        // this is a stop node for parent.right and parent.body
                        return false;

                    // EXCLUDES: e.g. cache.get(foo.a).b = 0;
                    case "CallExpression":
                        if (parent.callee !== node) {
                            return false;
                        }
                        break;

                    // EXCLUDES: e.g. cache[foo.a] = 0;
                    case "MemberExpression":
                        if (parent.property === node) {
                            return false;
                        }
                        break;

                    // EXCLUDES: e.g. ({ [foo]: a }) = bar;
                    case "Property":
                        if (parent.key === node) {
                            return false;
                        }

                        break;

                    // EXCLUDES: e.g. (foo ? a : b).c = bar;
                    case "ConditionalExpression":
                        if (parent.test === node) {
                            return false;
                        }

                        break;

                    // no default
                }

                node = parent;
                parent = node.parent;
            }

            return false;
        }

        /**
         * Tests that an identifier name matches any of the ignored property assignments.
         * First we test strings in ignoredPropertyAssignmentsFor.
         * Then we instantiate and test RegExp objects from ignoredPropertyAssignmentsForRegex strings.
         * @param {string} identifierName A string that describes the name of an identifier to
         * ignore property assignments for.
         * @returns {boolean} Whether the string matches an ignored property assignment regular expression or not.
         */
        function isIgnoredPropertyAssignment(identifierName) {
            return ignoredPropertyAssignmentsFor.includes(identifierName) ||
                ignoredPropertyAssignmentsForRegex.some(ignored => new RegExp(ignored, "u").test(identifierName));
        }

        /**
         * Reports a reference if is non initializer and writable.
         * @param {Reference} reference A reference to check.
         * @param {int} index The index of the reference in the references.
         * @param {Reference[]} references The array that the reference belongs to.
         * @returns {void}
         */
        function checkReference(reference, index, references) {
            const identifier = reference.identifier;

            if (identifier &&
                !reference.init &&

                /*
                 * Destructuring assignments can have multiple default value,
                 * so possibly there are multiple writeable references for the same identifier.
                 */
                (index === 0 || references[index - 1].identifier !== identifier)
            ) {
                if (reference.isWrite()) {
                    context.report({ node: identifier, message: "Assignment to function parameter '{{name}}'.", data: { name: identifier.name } });
                } else if (props && isModifyingProp(reference) && !isIgnoredPropertyAssignment(identifier.name)) {
                    context.report({ node: identifier, message: "Assignment to property of function parameter '{{name}}'.", data: { name: identifier.name } });
                }
            }
        }

        /**
         * Finds and reports references that are non initializer and writable.
         * @param {Variable} variable A variable to check.
         * @returns {void}
         */
        function checkVariable(variable) {
            if (variable.defs[0].type === "Parameter") {
                variable.references.forEach(checkReference);
            }
        }

        /**
         * Checks parameters of a given function node.
         * @param {ASTNode} node A function node to check.
         * @returns {void}
         */
        function checkForFunction(node) {
            context.getDeclaredVariables(node).forEach(checkVariable);
        }

        return {

            // `:exit` is needed for the `node.parent` property of identifier nodes.
            "FunctionDeclaration:exit": checkForFunction,
            "FunctionExpression:exit": checkForFunction,
            "ArrowFunctionExpression:exit": checkForFunction
        };

    }
};