require-atomic-updates.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. /**
  70. * Represents segment information.
  71. */
  72. class SegmentInfo {
  73. constructor() {
  74. this.info = new WeakMap();
  75. }
  76. /**
  77. * Initialize the segment information.
  78. * @param {PathSegment} segment The segment to initialize.
  79. * @returns {void}
  80. */
  81. initialize(segment) {
  82. const outdatedReadVariables = new Set();
  83. const freshReadVariables = new Set();
  84. for (const prevSegment of segment.prevSegments) {
  85. const info = this.info.get(prevSegment);
  86. if (info) {
  87. info.outdatedReadVariables.forEach(Set.prototype.add, outdatedReadVariables);
  88. info.freshReadVariables.forEach(Set.prototype.add, freshReadVariables);
  89. }
  90. }
  91. this.info.set(segment, { outdatedReadVariables, freshReadVariables });
  92. }
  93. /**
  94. * Mark a given variable as read on given segments.
  95. * @param {PathSegment[]} segments The segments that it read the variable on.
  96. * @param {Variable} variable The variable to be read.
  97. * @returns {void}
  98. */
  99. markAsRead(segments, variable) {
  100. for (const segment of segments) {
  101. const info = this.info.get(segment);
  102. if (info) {
  103. info.freshReadVariables.add(variable);
  104. // If a variable is freshly read again, then it's no more out-dated.
  105. info.outdatedReadVariables.delete(variable);
  106. }
  107. }
  108. }
  109. /**
  110. * Move `freshReadVariables` to `outdatedReadVariables`.
  111. * @param {PathSegment[]} segments The segments to process.
  112. * @returns {void}
  113. */
  114. makeOutdated(segments) {
  115. for (const segment of segments) {
  116. const info = this.info.get(segment);
  117. if (info) {
  118. info.freshReadVariables.forEach(Set.prototype.add, info.outdatedReadVariables);
  119. info.freshReadVariables.clear();
  120. }
  121. }
  122. }
  123. /**
  124. * Check if a given variable is outdated on the current segments.
  125. * @param {PathSegment[]} segments The current segments.
  126. * @param {Variable} variable The variable to check.
  127. * @returns {boolean} `true` if the variable is outdated on the segments.
  128. */
  129. isOutdated(segments, variable) {
  130. for (const segment of segments) {
  131. const info = this.info.get(segment);
  132. if (info && info.outdatedReadVariables.has(variable)) {
  133. return true;
  134. }
  135. }
  136. return false;
  137. }
  138. }
  139. //------------------------------------------------------------------------------
  140. // Rule Definition
  141. //------------------------------------------------------------------------------
  142. /** @type {import('../shared/types').Rule} */
  143. module.exports = {
  144. meta: {
  145. type: "problem",
  146. docs: {
  147. description: "Disallow assignments that can lead to race conditions due to usage of `await` or `yield`",
  148. recommended: false,
  149. url: "https://eslint.org/docs/rules/require-atomic-updates"
  150. },
  151. fixable: null,
  152. schema: [{
  153. type: "object",
  154. properties: {
  155. allowProperties: {
  156. type: "boolean",
  157. default: false
  158. }
  159. },
  160. additionalProperties: false
  161. }],
  162. messages: {
  163. nonAtomicUpdate: "Possible race condition: `{{value}}` might be reassigned based on an outdated value of `{{value}}`.",
  164. nonAtomicObjectUpdate: "Possible race condition: `{{value}}` might be assigned based on an outdated state of `{{object}}`."
  165. }
  166. },
  167. create(context) {
  168. const allowProperties = !!context.options[0] && context.options[0].allowProperties;
  169. const sourceCode = context.getSourceCode();
  170. const assignmentReferences = new Map();
  171. const segmentInfo = new SegmentInfo();
  172. let stack = null;
  173. return {
  174. onCodePathStart(codePath) {
  175. const scope = context.getScope();
  176. const shouldVerify =
  177. scope.type === "function" &&
  178. (scope.block.async || scope.block.generator);
  179. stack = {
  180. upper: stack,
  181. codePath,
  182. referenceMap: shouldVerify ? createReferenceMap(scope) : null
  183. };
  184. },
  185. onCodePathEnd() {
  186. stack = stack.upper;
  187. },
  188. // Initialize the segment information.
  189. onCodePathSegmentStart(segment) {
  190. segmentInfo.initialize(segment);
  191. },
  192. // Handle references to prepare verification.
  193. Identifier(node) {
  194. const { codePath, referenceMap } = stack;
  195. const reference = referenceMap && referenceMap.get(node);
  196. // Ignore if this is not a valid variable reference.
  197. if (!reference) {
  198. return;
  199. }
  200. const variable = reference.resolved;
  201. const writeExpr = getWriteExpr(reference);
  202. const isMemberAccess = reference.identifier.parent.type === "MemberExpression";
  203. // Add a fresh read variable.
  204. if (reference.isRead() && !(writeExpr && writeExpr.parent.operator === "=")) {
  205. segmentInfo.markAsRead(codePath.currentSegments, variable);
  206. }
  207. /*
  208. * Register the variable to verify after ESLint traversed the `writeExpr` node
  209. * if this reference is an assignment to a variable which is referred from other closure.
  210. */
  211. if (writeExpr &&
  212. writeExpr.parent.right === writeExpr && // ← exclude variable declarations.
  213. !isLocalVariableWithoutEscape(variable, isMemberAccess)
  214. ) {
  215. let refs = assignmentReferences.get(writeExpr);
  216. if (!refs) {
  217. refs = [];
  218. assignmentReferences.set(writeExpr, refs);
  219. }
  220. refs.push(reference);
  221. }
  222. },
  223. /*
  224. * Verify assignments.
  225. * If the reference exists in `outdatedReadVariables` list, report it.
  226. */
  227. ":expression:exit"(node) {
  228. const { codePath, referenceMap } = stack;
  229. // referenceMap exists if this is in a resumable function scope.
  230. if (!referenceMap) {
  231. return;
  232. }
  233. // Mark the read variables on this code path as outdated.
  234. if (node.type === "AwaitExpression" || node.type === "YieldExpression") {
  235. segmentInfo.makeOutdated(codePath.currentSegments);
  236. }
  237. // Verify.
  238. const references = assignmentReferences.get(node);
  239. if (references) {
  240. assignmentReferences.delete(node);
  241. for (const reference of references) {
  242. const variable = reference.resolved;
  243. if (segmentInfo.isOutdated(codePath.currentSegments, variable)) {
  244. if (node.parent.left === reference.identifier) {
  245. context.report({
  246. node: node.parent,
  247. messageId: "nonAtomicUpdate",
  248. data: {
  249. value: variable.name
  250. }
  251. });
  252. } else if (!allowProperties) {
  253. context.report({
  254. node: node.parent,
  255. messageId: "nonAtomicObjectUpdate",
  256. data: {
  257. value: sourceCode.getText(node.parent.left),
  258. object: variable.name
  259. }
  260. });
  261. }
  262. }
  263. }
  264. }
  265. }
  266. };
  267. }
  268. };