summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/lib/rules/require-atomic-updates.js
blob: e8dbe17b88dcd85e7ca7bbcb1f28d61b175c00b9 (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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/**
 * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield`
 * @author Teddy Katz
 */
"use strict";

const astUtils = require("../util/ast-utils");

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

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

        docs: {
            description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
            category: "Possible Errors",
            recommended: false,
            url: "https://eslint.org/docs/rules/require-atomic-updates"
        },

        fixable: null,
        schema: [],

        messages: {
            nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`."
        }
    },

    create(context) {
        const sourceCode = context.getSourceCode();
        const identifierToSurroundingFunctionMap = new WeakMap();
        const expressionsByCodePathSegment = new Map();

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        const resolvedVariableCache = new WeakMap();

        /**
         * Gets the variable scope around this variable reference
         * @param {ASTNode} identifier An `Identifier` AST node
         * @returns {Scope|null} An escope Scope
         */
        function getScope(identifier) {
            for (let currentNode = identifier; currentNode; currentNode = currentNode.parent) {
                const scope = sourceCode.scopeManager.acquire(currentNode, true);

                if (scope) {
                    return scope;
                }
            }
            return null;
        }

        /**
         * Resolves a given identifier to a given scope
         * @param {ASTNode} identifier An `Identifier` AST node
         * @param {Scope} scope An escope Scope
         * @returns {Variable|null} An escope Variable corresponding to the given identifier
         */
        function resolveVariableInScope(identifier, scope) {
            return scope.variables.find(variable => variable.name === identifier.name) ||
                (scope.upper ? resolveVariableInScope(identifier, scope.upper) : null);
        }

        /**
         * Resolves an identifier to a variable
         * @param {ASTNode} identifier An identifier node
         * @returns {Variable|null} The escope Variable that uses this identifier
         */
        function resolveVariable(identifier) {
            if (!resolvedVariableCache.has(identifier)) {
                const surroundingScope = getScope(identifier);

                if (surroundingScope) {
                    resolvedVariableCache.set(identifier, resolveVariableInScope(identifier, surroundingScope));
                } else {
                    resolvedVariableCache.set(identifier, null);
                }
            }

            return resolvedVariableCache.get(identifier);
        }

        /**
         * Checks if an expression is a variable that can only be observed within the given function.
         * @param {ASTNode} expression The expression to check
         * @param {ASTNode} surroundingFunction The function node
         * @returns {boolean} `true` if the expression is a variable which is local to the given function, and is never
         * referenced in a closure.
         */
        function isLocalVariableWithoutEscape(expression, surroundingFunction) {
            if (expression.type !== "Identifier") {
                return false;
            }

            const variable = resolveVariable(expression);

            if (!variable) {
                return false;
            }

            return variable.references.every(reference => identifierToSurroundingFunctionMap.get(reference.identifier) === surroundingFunction) &&
                variable.defs.every(def => identifierToSurroundingFunctionMap.get(def.name) === surroundingFunction);
        }

        /**
         * Reports an AssignmentExpression node that has a non-atomic update
         * @param {ASTNode} assignmentExpression The assignment that is potentially unsafe
         * @returns {void}
         */
        function reportAssignment(assignmentExpression) {
            context.report({
                node: assignmentExpression,
                messageId: "nonAtomicUpdate",
                data: {
                    value: sourceCode.getText(assignmentExpression.left)
                }
            });
        }

        const alreadyReportedAssignments = new WeakSet();

        class AssignmentTrackerState {
            constructor({ openAssignmentsWithoutReads = new Set(), openAssignmentsWithReads = new Set() } = {}) {
                this.openAssignmentsWithoutReads = openAssignmentsWithoutReads;
                this.openAssignmentsWithReads = openAssignmentsWithReads;
            }

            copy() {
                return new AssignmentTrackerState({
                    openAssignmentsWithoutReads: new Set(this.openAssignmentsWithoutReads),
                    openAssignmentsWithReads: new Set(this.openAssignmentsWithReads)
                });
            }

            merge(other) {
                const initialAssignmentsWithoutReadsCount = this.openAssignmentsWithoutReads.size;
                const initialAssignmentsWithReadsCount = this.openAssignmentsWithReads.size;

                other.openAssignmentsWithoutReads.forEach(assignment => this.openAssignmentsWithoutReads.add(assignment));
                other.openAssignmentsWithReads.forEach(assignment => this.openAssignmentsWithReads.add(assignment));

                return this.openAssignmentsWithoutReads.size > initialAssignmentsWithoutReadsCount ||
                    this.openAssignmentsWithReads.size > initialAssignmentsWithReadsCount;
            }

            enterAssignment(assignmentExpression) {
                (assignmentExpression.operator === "=" ? this.openAssignmentsWithoutReads : this.openAssignmentsWithReads).add(assignmentExpression);
            }

            exitAssignment(assignmentExpression) {
                this.openAssignmentsWithoutReads.delete(assignmentExpression);
                this.openAssignmentsWithReads.delete(assignmentExpression);
            }

            exitAwaitOrYield(node, surroundingFunction) {
                return [...this.openAssignmentsWithReads]
                    .filter(assignment => !isLocalVariableWithoutEscape(assignment.left, surroundingFunction))
                    .forEach(assignment => {
                        if (!alreadyReportedAssignments.has(assignment)) {
                            reportAssignment(assignment);
                            alreadyReportedAssignments.add(assignment);
                        }
                    });
            }

            exitIdentifierOrMemberExpression(node) {
                [...this.openAssignmentsWithoutReads]
                    .filter(assignment => (
                        assignment.left !== node &&
                        assignment.left.type === node.type &&
                        astUtils.equalTokens(assignment.left, node, sourceCode)
                    ))
                    .forEach(assignment => {
                        this.openAssignmentsWithoutReads.delete(assignment);
                        this.openAssignmentsWithReads.add(assignment);
                    });
            }
        }

        /**
         * If the control flow graph of a function enters an assignment expression, then does the
         * both of the following steps in order (possibly with other steps in between) before exiting the
         * assignment expression, then the assignment might be using an outdated value.
         * 1. Enters a read of the variable or property assigned in the expression (not necessary if operator assignment is used)
         * 2. Exits an `await` or `yield` expression
         *
         * This function checks for the outdated values and reports them.
         * @param {CodePathSegment} codePathSegment The current code path segment to traverse
         * @param {ASTNode} surroundingFunction The function node containing the code path segment
         * @returns {void}
         */
        function findOutdatedReads(
            codePathSegment,
            surroundingFunction,
            {
                stateBySegmentStart = new WeakMap(),
                stateBySegmentEnd = new WeakMap()
            } = {}
        ) {
            if (!stateBySegmentStart.has(codePathSegment)) {
                stateBySegmentStart.set(codePathSegment, new AssignmentTrackerState());
            }

            const currentState = stateBySegmentStart.get(codePathSegment).copy();

            expressionsByCodePathSegment.get(codePathSegment).forEach(({ entering, node }) => {
                if (node.type === "AssignmentExpression") {
                    if (entering) {
                        currentState.enterAssignment(node);
                    } else {
                        currentState.exitAssignment(node);
                    }
                } else if (!entering && (node.type === "AwaitExpression" || node.type === "YieldExpression")) {
                    currentState.exitAwaitOrYield(node, surroundingFunction);
                } else if (!entering && (node.type === "Identifier" || node.type === "MemberExpression")) {
                    currentState.exitIdentifierOrMemberExpression(node);
                }
            });

            stateBySegmentEnd.set(codePathSegment, currentState);

            codePathSegment.nextSegments.forEach(nextSegment => {
                if (stateBySegmentStart.has(nextSegment)) {
                    if (!stateBySegmentStart.get(nextSegment).merge(currentState)) {

                        /*
                         * This segment has already been processed with the given set of inputs;
                         * no need to do it again. After no new state is available to process
                         * for any control flow segment in the graph, the analysis reaches a fixpoint and
                         * traversal stops.
                         */
                        return;
                    }
                } else {
                    stateBySegmentStart.set(nextSegment, currentState.copy());
                }
                findOutdatedReads(
                    nextSegment,
                    surroundingFunction,
                    { stateBySegmentStart, stateBySegmentEnd }
                );
            });
        }

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        const currentCodePathSegmentStack = [];
        let currentCodePathSegment = null;
        const functionStack = [];

        return {
            onCodePathStart() {
                currentCodePathSegmentStack.push(currentCodePathSegment);
            },

            onCodePathEnd(codePath, node) {
                currentCodePathSegment = currentCodePathSegmentStack.pop();

                if (astUtils.isFunction(node) && (node.async || node.generator)) {
                    findOutdatedReads(codePath.initialSegment, node);
                }
            },

            onCodePathSegmentStart(segment) {
                currentCodePathSegment = segment;
                expressionsByCodePathSegment.set(segment, []);
            },

            "AssignmentExpression, Identifier, MemberExpression, AwaitExpression, YieldExpression"(node) {
                expressionsByCodePathSegment.get(currentCodePathSegment).push({ entering: true, node });
            },

            "AssignmentExpression, Identifier, MemberExpression, AwaitExpression, YieldExpression:exit"(node) {
                expressionsByCodePathSegment.get(currentCodePathSegment).push({ entering: false, node });
            },

            ":function"(node) {
                functionStack.push(node);
            },

            ":function:exit"() {
                functionStack.pop();
            },

            Identifier(node) {
                if (functionStack.length) {
                    identifierToSurroundingFunctionMap.set(node, functionStack[functionStack.length - 1]);
                }
            }
        };
    }
};