code-path.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /**
  2. * @fileoverview A class of the code path.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const CodePathState = require("./code-path-state");
  10. const IdGenerator = require("./id-generator");
  11. //------------------------------------------------------------------------------
  12. // Public Interface
  13. //------------------------------------------------------------------------------
  14. /**
  15. * A code path.
  16. */
  17. class CodePath {
  18. /**
  19. * Creates a new instance.
  20. * @param {Object} options Options for the function (see below).
  21. * @param {string} options.id An identifier.
  22. * @param {string} options.origin The type of code path origin.
  23. * @param {CodePath|null} options.upper The code path of the upper function scope.
  24. * @param {Function} options.onLooped A callback function to notify looping.
  25. */
  26. constructor({ id, origin, upper, onLooped }) {
  27. /**
  28. * The identifier of this code path.
  29. * Rules use it to store additional information of each rule.
  30. * @type {string}
  31. */
  32. this.id = id;
  33. /**
  34. * The reason that this code path was started. May be "program",
  35. * "function", "class-field-initializer", or "class-static-block".
  36. * @type {string}
  37. */
  38. this.origin = origin;
  39. /**
  40. * The code path of the upper function scope.
  41. * @type {CodePath|null}
  42. */
  43. this.upper = upper;
  44. /**
  45. * The code paths of nested function scopes.
  46. * @type {CodePath[]}
  47. */
  48. this.childCodePaths = [];
  49. // Initializes internal state.
  50. Object.defineProperty(this, "internal", {
  51. value: new CodePathState(new IdGenerator(`${id}_`), onLooped),
  52. });
  53. // Adds this into `childCodePaths` of `upper`.
  54. if (upper) {
  55. upper.childCodePaths.push(this);
  56. }
  57. }
  58. /**
  59. * Gets the state of a given code path.
  60. * @param {CodePath} codePath A code path to get.
  61. * @returns {CodePathState} The state of the code path.
  62. */
  63. static getState(codePath) {
  64. return codePath.internal;
  65. }
  66. /**
  67. * The initial code path segment. This is the segment that is at the head
  68. * of the code path.
  69. * This is a passthrough to the underlying `CodePathState`.
  70. * @type {CodePathSegment}
  71. */
  72. get initialSegment() {
  73. return this.internal.initialSegment;
  74. }
  75. /**
  76. * Final code path segments. These are the terminal (tail) segments in the
  77. * code path, which is the combination of `returnedSegments` and `thrownSegments`.
  78. * All segments in this array are reachable.
  79. * This is a passthrough to the underlying `CodePathState`.
  80. * @type {CodePathSegment[]}
  81. */
  82. get finalSegments() {
  83. return this.internal.finalSegments;
  84. }
  85. /**
  86. * Final code path segments that represent normal completion of the code path.
  87. * For functions, this means both explicit `return` statements and implicit returns,
  88. * such as the last reachable segment in a function that does not have an
  89. * explicit `return` as this implicitly returns `undefined`. For scripts,
  90. * modules, class field initializers, and class static blocks, this means
  91. * all lines of code have been executed.
  92. * These segments are also present in `finalSegments`.
  93. * This is a passthrough to the underlying `CodePathState`.
  94. * @type {CodePathSegment[]}
  95. */
  96. get returnedSegments() {
  97. return this.internal.returnedForkContext;
  98. }
  99. /**
  100. * Final code path segments that represent `throw` statements.
  101. * This is a passthrough to the underlying `CodePathState`.
  102. * These segments are also present in `finalSegments`.
  103. * @type {CodePathSegment[]}
  104. */
  105. get thrownSegments() {
  106. return this.internal.thrownForkContext;
  107. }
  108. /**
  109. * Traverses all segments in this code path.
  110. *
  111. * codePath.traverseSegments((segment, controller) => {
  112. * // do something.
  113. * });
  114. *
  115. * This method enumerates segments in order from the head.
  116. *
  117. * The `controller` argument has two methods:
  118. *
  119. * - `skip()` - skips the following segments in this branch
  120. * - `break()` - skips all following segments in the traversal
  121. *
  122. * A note on the parameters: the `options` argument is optional. This means
  123. * the first argument might be an options object or the callback function.
  124. * @param {Object} [optionsOrCallback] Optional first and last segments to traverse.
  125. * @param {CodePathSegment} [optionsOrCallback.first] The first segment to traverse.
  126. * @param {CodePathSegment} [optionsOrCallback.last] The last segment to traverse.
  127. * @param {Function} callback A callback function.
  128. * @returns {void}
  129. */
  130. traverseSegments(optionsOrCallback, callback) {
  131. // normalize the arguments into a callback and options
  132. let resolvedOptions;
  133. let resolvedCallback;
  134. if (typeof optionsOrCallback === "function") {
  135. resolvedCallback = optionsOrCallback;
  136. resolvedOptions = {};
  137. } else {
  138. resolvedOptions = optionsOrCallback || {};
  139. resolvedCallback = callback;
  140. }
  141. // determine where to start traversing from based on the options
  142. const startSegment =
  143. resolvedOptions.first || this.internal.initialSegment;
  144. const lastSegment = resolvedOptions.last;
  145. // set up initial location information
  146. let record;
  147. let index;
  148. let end;
  149. let segment = null;
  150. // segments that have already been visited during traversal
  151. const visited = new Set();
  152. // tracks the traversal steps
  153. const stack = [[startSegment, 0]];
  154. // segments that have been skipped during traversal
  155. const skipped = new Set();
  156. // indicates if we exited early from the traversal
  157. let broken = false;
  158. /**
  159. * Maintains traversal state.
  160. */
  161. const controller = {
  162. /**
  163. * Skip the following segments in this branch.
  164. * @returns {void}
  165. */
  166. skip() {
  167. skipped.add(segment);
  168. },
  169. /**
  170. * Stop traversal completely - do not traverse to any
  171. * other segments.
  172. * @returns {void}
  173. */
  174. break() {
  175. broken = true;
  176. },
  177. };
  178. /**
  179. * Checks if a given previous segment has been visited.
  180. * @param {CodePathSegment} prevSegment A previous segment to check.
  181. * @returns {boolean} `true` if the segment has been visited.
  182. */
  183. function isVisited(prevSegment) {
  184. return (
  185. visited.has(prevSegment) ||
  186. segment.isLoopedPrevSegment(prevSegment)
  187. );
  188. }
  189. /**
  190. * Checks if a given previous segment has been skipped.
  191. * @param {CodePathSegment} prevSegment A previous segment to check.
  192. * @returns {boolean} `true` if the segment has been skipped.
  193. */
  194. function isSkipped(prevSegment) {
  195. return (
  196. skipped.has(prevSegment) ||
  197. segment.isLoopedPrevSegment(prevSegment)
  198. );
  199. }
  200. // the traversal
  201. while (stack.length > 0) {
  202. /*
  203. * This isn't a pure stack. We use the top record all the time
  204. * but don't always pop it off. The record is popped only if
  205. * one of the following is true:
  206. *
  207. * 1) We have already visited the segment.
  208. * 2) We have not visited *all* of the previous segments.
  209. * 3) We have traversed past the available next segments.
  210. *
  211. * Otherwise, we just read the value and sometimes modify the
  212. * record as we traverse.
  213. */
  214. record = stack.at(-1);
  215. segment = record[0];
  216. index = record[1];
  217. if (index === 0) {
  218. // Skip if this segment has been visited already.
  219. if (visited.has(segment)) {
  220. stack.pop();
  221. continue;
  222. }
  223. // Skip if all previous segments have not been visited.
  224. if (
  225. segment !== startSegment &&
  226. segment.prevSegments.length > 0 &&
  227. !segment.prevSegments.every(isVisited)
  228. ) {
  229. stack.pop();
  230. continue;
  231. }
  232. visited.add(segment);
  233. // Skips the segment if all previous segments have been skipped.
  234. const shouldSkip =
  235. skipped.size > 0 &&
  236. segment.prevSegments.length > 0 &&
  237. segment.prevSegments.every(isSkipped);
  238. /*
  239. * If the most recent segment hasn't been skipped, then we call
  240. * the callback, passing in the segment and the controller.
  241. */
  242. if (!shouldSkip) {
  243. resolvedCallback.call(this, segment, controller);
  244. // exit if we're at the last segment
  245. if (segment === lastSegment) {
  246. controller.skip();
  247. }
  248. /*
  249. * If the previous statement was executed, or if the callback
  250. * called a method on the controller, we might need to exit the
  251. * loop, so check for that and break accordingly.
  252. */
  253. if (broken) {
  254. break;
  255. }
  256. } else {
  257. // If the most recent segment has been skipped, then mark it as skipped.
  258. skipped.add(segment);
  259. }
  260. }
  261. // Update the stack.
  262. end = segment.nextSegments.length - 1;
  263. if (index < end) {
  264. /*
  265. * If we haven't yet visited all of the next segments, update
  266. * the current top record on the stack to the next index to visit
  267. * and then push a record for the current segment on top.
  268. *
  269. * Setting the current top record's index lets us know how many
  270. * times we've been here and ensures that the segment won't be
  271. * reprocessed (because we only process segments with an index
  272. * of 0).
  273. */
  274. record[1] += 1;
  275. stack.push([segment.nextSegments[index], 0]);
  276. } else if (index === end) {
  277. /*
  278. * If we are at the last next segment, then reset the top record
  279. * in the stack to next segment and set its index to 0 so it will
  280. * be processed next.
  281. */
  282. record[0] = segment.nextSegments[index];
  283. record[1] = 0;
  284. } else {
  285. /*
  286. * If index > end, that means we have no more segments that need
  287. * processing. So, we pop that record off of the stack in order to
  288. * continue traversing at the next level up.
  289. */
  290. stack.pop();
  291. }
  292. }
  293. }
  294. }
  295. module.exports = CodePath;