code-path.js 11 KB

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