require-atomic-updates.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. /**
  2. * @fileoverview disallow assignments that can lead to race conditions due to usage of `await` or `yield`
  3. * @author Teddy Katz
  4. * @author Toru Nagashima
  5. */
  6. "use strict";
  7. /**
  8. * Make the map from identifiers to each reference.
  9. * @param {escope.Scope} scope The scope to get references.
  10. * @param {Map<Identifier, escope.Reference>} [outReferenceMap] The map from identifier nodes to each reference object.
  11. * @returns {Map<Identifier, escope.Reference>} `referenceMap`.
  12. */
  13. function createReferenceMap(scope, outReferenceMap = new Map()) {
  14. for (const reference of scope.references) {
  15. if (reference.resolved === null) {
  16. continue;
  17. }
  18. outReferenceMap.set(reference.identifier, reference);
  19. }
  20. for (const childScope of scope.childScopes) {
  21. if (childScope.type !== "function") {
  22. createReferenceMap(childScope, outReferenceMap);
  23. }
  24. }
  25. return outReferenceMap;
  26. }
  27. /**
  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`.
  32. */
  33. function getWriteExpr(reference) {
  34. if (reference.writeExpr) {
  35. return reference.writeExpr;
  36. }
  37. let node = reference.identifier;
  38. while (node) {
  39. const t = node.parent.type;
  40. if (t === "AssignmentExpression" && node.parent.left === node) {
  41. return node.parent.right;
  42. }
  43. if (t === "MemberExpression" && node.parent.object === node) {
  44. node = node.parent;
  45. continue;
  46. }
  47. break;
  48. }
  49. return null;
  50. }
  51. /**
  52. * Checks if an expression is a variable that can only be observed within the given function.
  53. * @param {Variable|null} variable The variable to check
  54. * @param {boolean} isMemberAccess If `true` then this is a member access.
  55. * @returns {boolean} `true` if the variable is local to the given function, and is never referenced in a closure.
  56. */
  57. function isLocalVariableWithoutEscape(variable, isMemberAccess) {
  58. if (!variable) {
  59. return false; // A global variable which was not defined.
  60. }
  61. // If the reference is a property access and the variable is a parameter, it handles the variable is not local.
  62. if (isMemberAccess && variable.defs.some(d => d.type === "Parameter")) {
  63. return false;
  64. }
  65. const functionScope = variable.scope.variableScope;
  66. return variable.references.every(reference =>
  67. reference.from.variableScope === functionScope);
  68. }
  69. class SegmentInfo {
  70. constructor() {
  71. this.info = new WeakMap();
  72. }
  73. /**
  74. * Initialize the segment information.
  75. * @param {PathSegment} segment The segment to initialize.
  76. * @returns {void}
  77. */
  78. initialize(segment) {
  79. const outdatedReadVariables = new Set();
  80. const freshReadVariables = new Set();
  81. for (const prevSegment of segment.prevSegments) {
  82. const info = this.info.get(prevSegment);
  83. if (info) {
  84. info.outdatedReadVariables.forEach(Set.prototype.add, outdatedReadVariables);
  85. info.freshReadVariables.forEach(Set.prototype.add, freshReadVariables);
  86. }
  87. }
  88. this.info.set(segment, { outdatedReadVariables, freshReadVariables });
  89. }
  90. /**
  91. * Mark a given variable as read on given segments.
  92. * @param {PathSegment[]} segments The segments that it read the variable on.
  93. * @param {Variable} variable The variable to be read.
  94. * @returns {void}
  95. */
  96. markAsRead(segments, variable) {
  97. for (const segment of segments) {
  98. const info = this.info.get(segment);
  99. if (info) {
  100. info.freshReadVariables.add(variable);
  101. // If a variable is freshly read again, then it's no more out-dated.
  102. info.outdatedReadVariables.delete(variable);
  103. }
  104. }
  105. }
  106. /**
  107. * Move `freshReadVariables` to `outdatedReadVariables`.
  108. * @param {PathSegment[]} segments The segments to process.
  109. * @returns {void}
  110. */
  111. makeOutdated(segments) {
  112. for (const segment of segments) {
  113. const info = this.info.get(segment);
  114. if (info) {
  115. info.freshReadVariables.forEach(Set.prototype.add, info.outdatedReadVariables);
  116. info.freshReadVariables.clear();
  117. }
  118. }
  119. }
  120. /**
  121. * Check if a given variable is outdated on the current segments.
  122. * @param {PathSegment[]} segments The current segments.
  123. * @param {Variable} variable The variable to check.
  124. * @returns {boolean} `true` if the variable is outdated on the segments.
  125. */
  126. isOutdated(segments, variable) {
  127. for (const segment of segments) {
  128. const info = this.info.get(segment);
  129. if (info && info.outdatedReadVariables.has(variable)) {
  130. return true;
  131. }
  132. }
  133. return false;
  134. }
  135. }
  136. //------------------------------------------------------------------------------
  137. // Rule Definition
  138. //------------------------------------------------------------------------------
  139. module.exports = {
  140. meta: {
  141. type: "problem",
  142. docs: {
  143. description: "disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
  144. category: "Possible Errors",
  145. recommended: false,
  146. url: "https://eslint.org/docs/rules/require-atomic-updates"
  147. },
  148. fixable: null,
  149. schema: [],
  150. messages: {
  151. nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`."
  152. }
  153. },
  154. create(context) {
  155. const sourceCode = context.getSourceCode();
  156. const assignmentReferences = new Map();
  157. const segmentInfo = new SegmentInfo();
  158. let stack = null;
  159. return {
  160. onCodePathStart(codePath) {
  161. const scope = context.getScope();
  162. const shouldVerify =
  163. scope.type === "function" &&
  164. (scope.block.async || scope.block.generator);
  165. stack = {
  166. upper: stack,
  167. codePath,
  168. referenceMap: shouldVerify ? createReferenceMap(scope) : null
  169. };
  170. },
  171. onCodePathEnd() {
  172. stack = stack.upper;
  173. },
  174. // Initialize the segment information.
  175. onCodePathSegmentStart(segment) {
  176. segmentInfo.initialize(segment);
  177. },
  178. // Handle references to prepare verification.
  179. Identifier(node) {
  180. const { codePath, referenceMap } = stack;
  181. const reference = referenceMap && referenceMap.get(node);
  182. // Ignore if this is not a valid variable reference.
  183. if (!reference) {
  184. return;
  185. }
  186. const variable = reference.resolved;
  187. const writeExpr = getWriteExpr(reference);
  188. const isMemberAccess = reference.identifier.parent.type === "MemberExpression";
  189. // Add a fresh read variable.
  190. if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) {
  191. segmentInfo.markAsRead(codePath.currentSegments, variable);
  192. }
  193. /*
  194. * Register the variable to verify after ESLint traversed the `writeExpr` node
  195. * if this reference is an assignment to a variable which is referred from other closure.
  196. */
  197. if (writeExpr &&
  198. writeExpr.parent.right === writeExpr && // ← exclude variable declarations.
  199. !isLocalVariableWithoutEscape(variable, isMemberAccess)
  200. ) {
  201. let refs = assignmentReferences.get(writeExpr);
  202. if (!refs) {
  203. refs = [];
  204. assignmentReferences.set(writeExpr, refs);
  205. }
  206. refs.push(reference);
  207. }
  208. },
  209. /*
  210. * Verify assignments.
  211. * If the reference exists in `outdatedReadVariables` list, report it.
  212. */
  213. ":expression:exit"(node) {
  214. const { codePath, referenceMap } = stack;
  215. // referenceMap exists if this is in a resumable function scope.
  216. if (!referenceMap) {
  217. return;
  218. }
  219. // Mark the read variables on this code path as outdated.
  220. if (node.type === "AwaitExpression" || node.type === "YieldExpression") {
  221. segmentInfo.makeOutdated(codePath.currentSegments);
  222. }
  223. // Verify.
  224. const references = assignmentReferences.get(node);
  225. if (references) {
  226. assignmentReferences.delete(node);
  227. for (const reference of references) {
  228. const variable = reference.resolved;
  229. if (segmentInfo.isOutdated(codePath.currentSegments, variable)) {
  230. context.report({
  231. node: node.parent,
  232. messageId: "nonAtomicUpdate",
  233. data: {
  234. value: sourceCode.getText(node.parent.left)
  235. }
  236. });
  237. }
  238. }
  239. }
  240. }
  241. };
  242. }
  243. };