2 * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield`
4 * @author Toru Nagashima
9 * Make the map from identifiers to each reference.
10 * @param {escope.Scope} scope The scope to get references.
11 * @param {Map<Identifier, escope.Reference>} [outReferenceMap] The map from identifier nodes to each reference object.
12 * @returns {Map<Identifier, escope.Reference>} `referenceMap`.
14 function createReferenceMap(scope, outReferenceMap = new Map()) {
15 for (const reference of scope.references) {
16 outReferenceMap.set(reference.identifier, reference);
18 for (const childScope of scope.childScopes) {
19 if (childScope.type !== "function") {
20 createReferenceMap(childScope, outReferenceMap);
24 return outReferenceMap;
28 * Get `reference.writeExpr` of a given reference.
29 * If it's the read reference of MemberExpression in LHS, returns RHS in order to address `a.b = await a`
30 * @param {escope.Reference} reference The reference to get.
31 * @returns {Expression|null} The `reference.writeExpr`.
33 function getWriteExpr(reference) {
34 if (reference.writeExpr) {
35 return reference.writeExpr;
37 let node = reference.identifier;
40 const t = node.parent.type;
42 if (t === "AssignmentExpression" && node.parent.left === node) {
43 return node.parent.right;
45 if (t === "MemberExpression" && node.parent.object === node) {
57 * Checks if an expression is a variable that can only be observed within the given function.
58 * @param {Variable|null} variable The variable to check
59 * @param {boolean} isMemberAccess If `true` then this is a member access.
60 * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure.
62 function isLocalVariableWithoutEscape(variable, isMemberAccess) {
64 return false; // A global variable which was not defined.
67 // If the reference is a property access and the variable is a parameter, it handles the variable is not local.
68 if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) {
72 const functionScope = variable.scope.variableScope;
74 return variable.references.every(reference =>
75 reference.from.variableScope === functionScope);
80 this.info = new WeakMap();
84 * Initialize the segment information.
85 * @param {PathSegment} segment The segment to initialize.
89 const outdatedReadVariableNames = new Set();
90 const freshReadVariableNames = new Set();
92 for (const prevSegment of segment.prevSegments) {
93 const info = this.info.get(prevSegment);
96 info.outdatedReadVariableNames.forEach(Set.prototype.add, outdatedReadVariableNames);
97 info.freshReadVariableNames.forEach(Set.prototype.add, freshReadVariableNames);
101 this.info.set(segment, { outdatedReadVariableNames, freshReadVariableNames });
105 * Mark a given variable as read on given segments.
106 * @param {PathSegment[]} segments The segments that it read the variable on.
107 * @param {string} variableName The variable name to be read.
110 markAsRead(segments, variableName) {
111 for (const segment of segments) {
112 const info = this.info.get(segment);
115 info.freshReadVariableNames.add(variableName);
121 * Move `freshReadVariableNames` to `outdatedReadVariableNames`.
122 * @param {PathSegment[]} segments The segments to process.
125 makeOutdated(segments) {
126 for (const segment of segments) {
127 const info = this.info.get(segment);
130 info.freshReadVariableNames.forEach(Set.prototype.add, info.outdatedReadVariableNames);
131 info.freshReadVariableNames.clear();
137 * Check if a given variable is outdated on the current segments.
138 * @param {PathSegment[]} segments The current segments.
139 * @param {string} variableName The variable name to check.
140 * @returns {boolean} `true` if the variable is outdated on the segments.
142 isOutdated(segments, variableName) {
143 for (const segment of segments) {
144 const info = this.info.get(segment);
146 if (info && info.outdatedReadVariableNames.has(variableName)) {
154 //------------------------------------------------------------------------------
156 //------------------------------------------------------------------------------
163 description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
164 category: "Possible Errors",
166 url: "https://eslint.org/docs/rules/require-atomic-updates"
173 nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`."
178 const sourceCode = context.getSourceCode();
179 const assignmentReferences = new Map();
180 const segmentInfo = new SegmentInfo();
184 onCodePathStart(codePath) {
185 const scope = context.getScope();
187 scope.type === "function" &&
188 (scope.block.async || scope.block.generator);
193 referenceMap: shouldVerify ? createReferenceMap(scope) : null
200 // Initialize the segment information.
201 onCodePathSegmentStart(segment) {
202 segmentInfo.initialize(segment);
205 // Handle references to prepare verification.
207 const { codePath, referenceMap } = stack;
208 const reference = referenceMap && referenceMap.get(node);
210 // Ignore if this is not a valid variable reference.
214 const name = reference.identifier.name;
215 const variable = reference.resolved;
216 const writeExpr = getWriteExpr(reference);
217 const isMemberAccess = reference.identifier.parent.type === "MemberExpression";
219 // Add a fresh read variable.
220 if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) {
221 segmentInfo.markAsRead(codePath.currentSegments, name);
225 * Register the variable to verify after ESLint traversed the `writeExpr` node
226 * if this reference is an assignment to a variable which is referred from other clausure.
229 writeExpr.parent.right === writeExpr && // ← exclude variable declarations.
230 !isLocalVariableWithoutEscape(variable, isMemberAccess)
232 let refs = assignmentReferences.get(writeExpr);
236 assignmentReferences.set(writeExpr, refs);
239 refs.push(reference);
244 * Verify assignments.
245 * If the reference exists in `outdatedReadVariableNames` list, report it.
247 ":expression:exit"(node) {
248 const { codePath, referenceMap } = stack;
250 // referenceMap exists if this is in a resumable function scope.
255 // Mark the read variables on this code path as outdated.
256 if (node.type === "AwaitExpression" || node.type === "YieldExpression") {
257 segmentInfo.makeOutdated(codePath.currentSegments);
261 const references = assignmentReferences.get(node);
264 assignmentReferences.delete(node);
266 for (const reference of references) {
267 const name = reference.identifier.name;
269 if (segmentInfo.isOutdated(codePath.currentSegments, name)) {
272 messageId: "nonAtomicUpdate",
274 value: sourceCode.getText(node.parent.left)