code-path-state.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. /**
  2. * @fileoverview A class to manage state of generating a code path.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const CodePathSegment = require("./code-path-segment"),
  10. ForkContext = require("./fork-context");
  11. //------------------------------------------------------------------------------
  12. // Helpers
  13. //------------------------------------------------------------------------------
  14. /**
  15. * Adds given segments into the `dest` array.
  16. * If the `others` array does not includes the given segments, adds to the `all`
  17. * array as well.
  18. *
  19. * This adds only reachable and used segments.
  20. * @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`).
  21. * @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`).
  22. * @param {CodePathSegment[]} all The unified destination array (`finalSegments`).
  23. * @param {CodePathSegment[]} segments Segments to add.
  24. * @returns {void}
  25. */
  26. function addToReturnedOrThrown(dest, others, all, segments) {
  27. for (let i = 0; i < segments.length; ++i) {
  28. const segment = segments[i];
  29. dest.push(segment);
  30. if (others.indexOf(segment) === -1) {
  31. all.push(segment);
  32. }
  33. }
  34. }
  35. /**
  36. * Gets a loop-context for a `continue` statement.
  37. * @param {CodePathState} state A state to get.
  38. * @param {string} label The label of a `continue` statement.
  39. * @returns {LoopContext} A loop-context for a `continue` statement.
  40. */
  41. function getContinueContext(state, label) {
  42. if (!label) {
  43. return state.loopContext;
  44. }
  45. let context = state.loopContext;
  46. while (context) {
  47. if (context.label === label) {
  48. return context;
  49. }
  50. context = context.upper;
  51. }
  52. /* istanbul ignore next: foolproof (syntax error) */
  53. return null;
  54. }
  55. /**
  56. * Gets a context for a `break` statement.
  57. * @param {CodePathState} state A state to get.
  58. * @param {string} label The label of a `break` statement.
  59. * @returns {LoopContext|SwitchContext} A context for a `break` statement.
  60. */
  61. function getBreakContext(state, label) {
  62. let context = state.breakContext;
  63. while (context) {
  64. if (label ? context.label === label : context.breakable) {
  65. return context;
  66. }
  67. context = context.upper;
  68. }
  69. /* istanbul ignore next: foolproof (syntax error) */
  70. return null;
  71. }
  72. /**
  73. * Gets a context for a `return` statement.
  74. * @param {CodePathState} state A state to get.
  75. * @returns {TryContext|CodePathState} A context for a `return` statement.
  76. */
  77. function getReturnContext(state) {
  78. let context = state.tryContext;
  79. while (context) {
  80. if (context.hasFinalizer && context.position !== "finally") {
  81. return context;
  82. }
  83. context = context.upper;
  84. }
  85. return state;
  86. }
  87. /**
  88. * Gets a context for a `throw` statement.
  89. * @param {CodePathState} state A state to get.
  90. * @returns {TryContext|CodePathState} A context for a `throw` statement.
  91. */
  92. function getThrowContext(state) {
  93. let context = state.tryContext;
  94. while (context) {
  95. if (context.position === "try" ||
  96. (context.hasFinalizer && context.position === "catch")
  97. ) {
  98. return context;
  99. }
  100. context = context.upper;
  101. }
  102. return state;
  103. }
  104. /**
  105. * Removes a given element from a given array.
  106. * @param {any[]} xs An array to remove the specific element.
  107. * @param {any} x An element to be removed.
  108. * @returns {void}
  109. */
  110. function remove(xs, x) {
  111. xs.splice(xs.indexOf(x), 1);
  112. }
  113. /**
  114. * Disconnect given segments.
  115. *
  116. * This is used in a process for switch statements.
  117. * If there is the "default" chunk before other cases, the order is different
  118. * between node's and running's.
  119. * @param {CodePathSegment[]} prevSegments Forward segments to disconnect.
  120. * @param {CodePathSegment[]} nextSegments Backward segments to disconnect.
  121. * @returns {void}
  122. */
  123. function removeConnection(prevSegments, nextSegments) {
  124. for (let i = 0; i < prevSegments.length; ++i) {
  125. const prevSegment = prevSegments[i];
  126. const nextSegment = nextSegments[i];
  127. remove(prevSegment.nextSegments, nextSegment);
  128. remove(prevSegment.allNextSegments, nextSegment);
  129. remove(nextSegment.prevSegments, prevSegment);
  130. remove(nextSegment.allPrevSegments, prevSegment);
  131. }
  132. }
  133. /**
  134. * Creates looping path.
  135. * @param {CodePathState} state The instance.
  136. * @param {CodePathSegment[]} unflattenedFromSegments Segments which are source.
  137. * @param {CodePathSegment[]} unflattenedToSegments Segments which are destination.
  138. * @returns {void}
  139. */
  140. function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) {
  141. const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments);
  142. const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments);
  143. const end = Math.min(fromSegments.length, toSegments.length);
  144. for (let i = 0; i < end; ++i) {
  145. const fromSegment = fromSegments[i];
  146. const toSegment = toSegments[i];
  147. if (toSegment.reachable) {
  148. fromSegment.nextSegments.push(toSegment);
  149. }
  150. if (fromSegment.reachable) {
  151. toSegment.prevSegments.push(fromSegment);
  152. }
  153. fromSegment.allNextSegments.push(toSegment);
  154. toSegment.allPrevSegments.push(fromSegment);
  155. if (toSegment.allPrevSegments.length >= 2) {
  156. CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment);
  157. }
  158. state.notifyLooped(fromSegment, toSegment);
  159. }
  160. }
  161. /**
  162. * Finalizes segments of `test` chunk of a ForStatement.
  163. *
  164. * - Adds `false` paths to paths which are leaving from the loop.
  165. * - Sets `true` paths to paths which go to the body.
  166. * @param {LoopContext} context A loop context to modify.
  167. * @param {ChoiceContext} choiceContext A choice context of this loop.
  168. * @param {CodePathSegment[]} head The current head paths.
  169. * @returns {void}
  170. */
  171. function finalizeTestSegmentsOfFor(context, choiceContext, head) {
  172. if (!choiceContext.processed) {
  173. choiceContext.trueForkContext.add(head);
  174. choiceContext.falseForkContext.add(head);
  175. }
  176. if (context.test !== true) {
  177. context.brokenForkContext.addAll(choiceContext.falseForkContext);
  178. }
  179. context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1);
  180. }
  181. //------------------------------------------------------------------------------
  182. // Public Interface
  183. //------------------------------------------------------------------------------
  184. /**
  185. * A class which manages state to analyze code paths.
  186. */
  187. class CodePathState {
  188. // eslint-disable-next-line jsdoc/require-description
  189. /**
  190. * @param {IdGenerator} idGenerator An id generator to generate id for code
  191. * path segments.
  192. * @param {Function} onLooped A callback function to notify looping.
  193. */
  194. constructor(idGenerator, onLooped) {
  195. this.idGenerator = idGenerator;
  196. this.notifyLooped = onLooped;
  197. this.forkContext = ForkContext.newRoot(idGenerator);
  198. this.choiceContext = null;
  199. this.switchContext = null;
  200. this.tryContext = null;
  201. this.loopContext = null;
  202. this.breakContext = null;
  203. this.currentSegments = [];
  204. this.initialSegment = this.forkContext.head[0];
  205. // returnedSegments and thrownSegments push elements into finalSegments also.
  206. const final = this.finalSegments = [];
  207. const returned = this.returnedForkContext = [];
  208. const thrown = this.thrownForkContext = [];
  209. returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final);
  210. thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final);
  211. }
  212. /**
  213. * The head segments.
  214. * @type {CodePathSegment[]}
  215. */
  216. get headSegments() {
  217. return this.forkContext.head;
  218. }
  219. /**
  220. * The parent forking context.
  221. * This is used for the root of new forks.
  222. * @type {ForkContext}
  223. */
  224. get parentForkContext() {
  225. const current = this.forkContext;
  226. return current && current.upper;
  227. }
  228. /**
  229. * Creates and stacks new forking context.
  230. * @param {boolean} forkLeavingPath A flag which shows being in a
  231. * "finally" block.
  232. * @returns {ForkContext} The created context.
  233. */
  234. pushForkContext(forkLeavingPath) {
  235. this.forkContext = ForkContext.newEmpty(
  236. this.forkContext,
  237. forkLeavingPath
  238. );
  239. return this.forkContext;
  240. }
  241. /**
  242. * Pops and merges the last forking context.
  243. * @returns {ForkContext} The last context.
  244. */
  245. popForkContext() {
  246. const lastContext = this.forkContext;
  247. this.forkContext = lastContext.upper;
  248. this.forkContext.replaceHead(lastContext.makeNext(0, -1));
  249. return lastContext;
  250. }
  251. /**
  252. * Creates a new path.
  253. * @returns {void}
  254. */
  255. forkPath() {
  256. this.forkContext.add(this.parentForkContext.makeNext(-1, -1));
  257. }
  258. /**
  259. * Creates a bypass path.
  260. * This is used for such as IfStatement which does not have "else" chunk.
  261. * @returns {void}
  262. */
  263. forkBypassPath() {
  264. this.forkContext.add(this.parentForkContext.head);
  265. }
  266. //--------------------------------------------------------------------------
  267. // ConditionalExpression, LogicalExpression, IfStatement
  268. //--------------------------------------------------------------------------
  269. /**
  270. * Creates a context for ConditionalExpression, LogicalExpression,
  271. * IfStatement, WhileStatement, DoWhileStatement, or ForStatement.
  272. *
  273. * LogicalExpressions have cases that it goes different paths between the
  274. * `true` case and the `false` case.
  275. *
  276. * For Example:
  277. *
  278. * if (a || b) {
  279. * foo();
  280. * } else {
  281. * bar();
  282. * }
  283. *
  284. * In this case, `b` is evaluated always in the code path of the `else`
  285. * block, but it's not so in the code path of the `if` block.
  286. * So there are 3 paths.
  287. *
  288. * a -> foo();
  289. * a -> b -> foo();
  290. * a -> b -> bar();
  291. * @param {string} kind A kind string.
  292. * If the new context is LogicalExpression's, this is `"&&"` or `"||"`.
  293. * If it's IfStatement's or ConditionalExpression's, this is `"test"`.
  294. * Otherwise, this is `"loop"`.
  295. * @param {boolean} isForkingAsResult A flag that shows that goes different
  296. * paths between `true` and `false`.
  297. * @returns {void}
  298. */
  299. pushChoiceContext(kind, isForkingAsResult) {
  300. this.choiceContext = {
  301. upper: this.choiceContext,
  302. kind,
  303. isForkingAsResult,
  304. trueForkContext: ForkContext.newEmpty(this.forkContext),
  305. falseForkContext: ForkContext.newEmpty(this.forkContext),
  306. processed: false
  307. };
  308. }
  309. /**
  310. * Pops the last choice context and finalizes it.
  311. * @returns {ChoiceContext} The popped context.
  312. */
  313. popChoiceContext() {
  314. const context = this.choiceContext;
  315. this.choiceContext = context.upper;
  316. const forkContext = this.forkContext;
  317. const headSegments = forkContext.head;
  318. switch (context.kind) {
  319. case "&&":
  320. case "||":
  321. /*
  322. * If any result were not transferred from child contexts,
  323. * this sets the head segments to both cases.
  324. * The head segments are the path of the right-hand operand.
  325. */
  326. if (!context.processed) {
  327. context.trueForkContext.add(headSegments);
  328. context.falseForkContext.add(headSegments);
  329. }
  330. /*
  331. * Transfers results to upper context if this context is in
  332. * test chunk.
  333. */
  334. if (context.isForkingAsResult) {
  335. const parentContext = this.choiceContext;
  336. parentContext.trueForkContext.addAll(context.trueForkContext);
  337. parentContext.falseForkContext.addAll(context.falseForkContext);
  338. parentContext.processed = true;
  339. return context;
  340. }
  341. break;
  342. case "test":
  343. if (!context.processed) {
  344. /*
  345. * The head segments are the path of the `if` block here.
  346. * Updates the `true` path with the end of the `if` block.
  347. */
  348. context.trueForkContext.clear();
  349. context.trueForkContext.add(headSegments);
  350. } else {
  351. /*
  352. * The head segments are the path of the `else` block here.
  353. * Updates the `false` path with the end of the `else`
  354. * block.
  355. */
  356. context.falseForkContext.clear();
  357. context.falseForkContext.add(headSegments);
  358. }
  359. break;
  360. case "loop":
  361. /*
  362. * Loops are addressed in popLoopContext().
  363. * This is called from popLoopContext().
  364. */
  365. return context;
  366. /* istanbul ignore next */
  367. default:
  368. throw new Error("unreachable");
  369. }
  370. // Merges all paths.
  371. const prevForkContext = context.trueForkContext;
  372. prevForkContext.addAll(context.falseForkContext);
  373. forkContext.replaceHead(prevForkContext.makeNext(0, -1));
  374. return context;
  375. }
  376. /**
  377. * Makes a code path segment of the right-hand operand of a logical
  378. * expression.
  379. * @returns {void}
  380. */
  381. makeLogicalRight() {
  382. const context = this.choiceContext;
  383. const forkContext = this.forkContext;
  384. if (context.processed) {
  385. /*
  386. * This got segments already from the child choice context.
  387. * Creates the next path from own true/false fork context.
  388. */
  389. const prevForkContext =
  390. context.kind === "&&" ? context.trueForkContext
  391. /* kind === "||" */ : context.falseForkContext;
  392. forkContext.replaceHead(prevForkContext.makeNext(0, -1));
  393. prevForkContext.clear();
  394. context.processed = false;
  395. } else {
  396. /*
  397. * This did not get segments from the child choice context.
  398. * So addresses the head segments.
  399. * The head segments are the path of the left-hand operand.
  400. */
  401. if (context.kind === "&&") {
  402. // The path does short-circuit if false.
  403. context.falseForkContext.add(forkContext.head);
  404. } else {
  405. // The path does short-circuit if true.
  406. context.trueForkContext.add(forkContext.head);
  407. }
  408. forkContext.replaceHead(forkContext.makeNext(-1, -1));
  409. }
  410. }
  411. /**
  412. * Makes a code path segment of the `if` block.
  413. * @returns {void}
  414. */
  415. makeIfConsequent() {
  416. const context = this.choiceContext;
  417. const forkContext = this.forkContext;
  418. /*
  419. * If any result were not transferred from child contexts,
  420. * this sets the head segments to both cases.
  421. * The head segments are the path of the test expression.
  422. */
  423. if (!context.processed) {
  424. context.trueForkContext.add(forkContext.head);
  425. context.falseForkContext.add(forkContext.head);
  426. }
  427. context.processed = false;
  428. // Creates new path from the `true` case.
  429. forkContext.replaceHead(
  430. context.trueForkContext.makeNext(0, -1)
  431. );
  432. }
  433. /**
  434. * Makes a code path segment of the `else` block.
  435. * @returns {void}
  436. */
  437. makeIfAlternate() {
  438. const context = this.choiceContext;
  439. const forkContext = this.forkContext;
  440. /*
  441. * The head segments are the path of the `if` block.
  442. * Updates the `true` path with the end of the `if` block.
  443. */
  444. context.trueForkContext.clear();
  445. context.trueForkContext.add(forkContext.head);
  446. context.processed = true;
  447. // Creates new path from the `false` case.
  448. forkContext.replaceHead(
  449. context.falseForkContext.makeNext(0, -1)
  450. );
  451. }
  452. //--------------------------------------------------------------------------
  453. // SwitchStatement
  454. //--------------------------------------------------------------------------
  455. /**
  456. * Creates a context object of SwitchStatement and stacks it.
  457. * @param {boolean} hasCase `true` if the switch statement has one or more
  458. * case parts.
  459. * @param {string|null} label The label text.
  460. * @returns {void}
  461. */
  462. pushSwitchContext(hasCase, label) {
  463. this.switchContext = {
  464. upper: this.switchContext,
  465. hasCase,
  466. defaultSegments: null,
  467. defaultBodySegments: null,
  468. foundDefault: false,
  469. lastIsDefault: false,
  470. countForks: 0
  471. };
  472. this.pushBreakContext(true, label);
  473. }
  474. /**
  475. * Pops the last context of SwitchStatement and finalizes it.
  476. *
  477. * - Disposes all forking stack for `case` and `default`.
  478. * - Creates the next code path segment from `context.brokenForkContext`.
  479. * - If the last `SwitchCase` node is not a `default` part, creates a path
  480. * to the `default` body.
  481. * @returns {void}
  482. */
  483. popSwitchContext() {
  484. const context = this.switchContext;
  485. this.switchContext = context.upper;
  486. const forkContext = this.forkContext;
  487. const brokenForkContext = this.popBreakContext().brokenForkContext;
  488. if (context.countForks === 0) {
  489. /*
  490. * When there is only one `default` chunk and there is one or more
  491. * `break` statements, even if forks are nothing, it needs to merge
  492. * those.
  493. */
  494. if (!brokenForkContext.empty) {
  495. brokenForkContext.add(forkContext.makeNext(-1, -1));
  496. forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
  497. }
  498. return;
  499. }
  500. const lastSegments = forkContext.head;
  501. this.forkBypassPath();
  502. const lastCaseSegments = forkContext.head;
  503. /*
  504. * `brokenForkContext` is used to make the next segment.
  505. * It must add the last segment into `brokenForkContext`.
  506. */
  507. brokenForkContext.add(lastSegments);
  508. /*
  509. * A path which is failed in all case test should be connected to path
  510. * of `default` chunk.
  511. */
  512. if (!context.lastIsDefault) {
  513. if (context.defaultBodySegments) {
  514. /*
  515. * Remove a link from `default` label to its chunk.
  516. * It's false route.
  517. */
  518. removeConnection(context.defaultSegments, context.defaultBodySegments);
  519. makeLooped(this, lastCaseSegments, context.defaultBodySegments);
  520. } else {
  521. /*
  522. * It handles the last case body as broken if `default` chunk
  523. * does not exist.
  524. */
  525. brokenForkContext.add(lastCaseSegments);
  526. }
  527. }
  528. // Pops the segment context stack until the entry segment.
  529. for (let i = 0; i < context.countForks; ++i) {
  530. this.forkContext = this.forkContext.upper;
  531. }
  532. /*
  533. * Creates a path from all brokenForkContext paths.
  534. * This is a path after switch statement.
  535. */
  536. this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
  537. }
  538. /**
  539. * Makes a code path segment for a `SwitchCase` node.
  540. * @param {boolean} isEmpty `true` if the body is empty.
  541. * @param {boolean} isDefault `true` if the body is the default case.
  542. * @returns {void}
  543. */
  544. makeSwitchCaseBody(isEmpty, isDefault) {
  545. const context = this.switchContext;
  546. if (!context.hasCase) {
  547. return;
  548. }
  549. /*
  550. * Merge forks.
  551. * The parent fork context has two segments.
  552. * Those are from the current case and the body of the previous case.
  553. */
  554. const parentForkContext = this.forkContext;
  555. const forkContext = this.pushForkContext();
  556. forkContext.add(parentForkContext.makeNext(0, -1));
  557. /*
  558. * Save `default` chunk info.
  559. * If the `default` label is not at the last, we must make a path from
  560. * the last `case` to the `default` chunk.
  561. */
  562. if (isDefault) {
  563. context.defaultSegments = parentForkContext.head;
  564. if (isEmpty) {
  565. context.foundDefault = true;
  566. } else {
  567. context.defaultBodySegments = forkContext.head;
  568. }
  569. } else {
  570. if (!isEmpty && context.foundDefault) {
  571. context.foundDefault = false;
  572. context.defaultBodySegments = forkContext.head;
  573. }
  574. }
  575. context.lastIsDefault = isDefault;
  576. context.countForks += 1;
  577. }
  578. //--------------------------------------------------------------------------
  579. // TryStatement
  580. //--------------------------------------------------------------------------
  581. /**
  582. * Creates a context object of TryStatement and stacks it.
  583. * @param {boolean} hasFinalizer `true` if the try statement has a
  584. * `finally` block.
  585. * @returns {void}
  586. */
  587. pushTryContext(hasFinalizer) {
  588. this.tryContext = {
  589. upper: this.tryContext,
  590. position: "try",
  591. hasFinalizer,
  592. returnedForkContext: hasFinalizer
  593. ? ForkContext.newEmpty(this.forkContext)
  594. : null,
  595. thrownForkContext: ForkContext.newEmpty(this.forkContext),
  596. lastOfTryIsReachable: false,
  597. lastOfCatchIsReachable: false
  598. };
  599. }
  600. /**
  601. * Pops the last context of TryStatement and finalizes it.
  602. * @returns {void}
  603. */
  604. popTryContext() {
  605. const context = this.tryContext;
  606. this.tryContext = context.upper;
  607. if (context.position === "catch") {
  608. // Merges two paths from the `try` block and `catch` block merely.
  609. this.popForkContext();
  610. return;
  611. }
  612. /*
  613. * The following process is executed only when there is the `finally`
  614. * block.
  615. */
  616. const returned = context.returnedForkContext;
  617. const thrown = context.thrownForkContext;
  618. if (returned.empty && thrown.empty) {
  619. return;
  620. }
  621. // Separate head to normal paths and leaving paths.
  622. const headSegments = this.forkContext.head;
  623. this.forkContext = this.forkContext.upper;
  624. const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0);
  625. const leavingSegments = headSegments.slice(headSegments.length / 2 | 0);
  626. // Forwards the leaving path to upper contexts.
  627. if (!returned.empty) {
  628. getReturnContext(this).returnedForkContext.add(leavingSegments);
  629. }
  630. if (!thrown.empty) {
  631. getThrowContext(this).thrownForkContext.add(leavingSegments);
  632. }
  633. // Sets the normal path as the next.
  634. this.forkContext.replaceHead(normalSegments);
  635. /*
  636. * If both paths of the `try` block and the `catch` block are
  637. * unreachable, the next path becomes unreachable as well.
  638. */
  639. if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) {
  640. this.forkContext.makeUnreachable();
  641. }
  642. }
  643. /**
  644. * Makes a code path segment for a `catch` block.
  645. * @returns {void}
  646. */
  647. makeCatchBlock() {
  648. const context = this.tryContext;
  649. const forkContext = this.forkContext;
  650. const thrown = context.thrownForkContext;
  651. // Update state.
  652. context.position = "catch";
  653. context.thrownForkContext = ForkContext.newEmpty(forkContext);
  654. context.lastOfTryIsReachable = forkContext.reachable;
  655. // Merge thrown paths.
  656. thrown.add(forkContext.head);
  657. const thrownSegments = thrown.makeNext(0, -1);
  658. // Fork to a bypass and the merged thrown path.
  659. this.pushForkContext();
  660. this.forkBypassPath();
  661. this.forkContext.add(thrownSegments);
  662. }
  663. /**
  664. * Makes a code path segment for a `finally` block.
  665. *
  666. * In the `finally` block, parallel paths are created. The parallel paths
  667. * are used as leaving-paths. The leaving-paths are paths from `return`
  668. * statements and `throw` statements in a `try` block or a `catch` block.
  669. * @returns {void}
  670. */
  671. makeFinallyBlock() {
  672. const context = this.tryContext;
  673. let forkContext = this.forkContext;
  674. const returned = context.returnedForkContext;
  675. const thrown = context.thrownForkContext;
  676. const headOfLeavingSegments = forkContext.head;
  677. // Update state.
  678. if (context.position === "catch") {
  679. // Merges two paths from the `try` block and `catch` block.
  680. this.popForkContext();
  681. forkContext = this.forkContext;
  682. context.lastOfCatchIsReachable = forkContext.reachable;
  683. } else {
  684. context.lastOfTryIsReachable = forkContext.reachable;
  685. }
  686. context.position = "finally";
  687. if (returned.empty && thrown.empty) {
  688. // This path does not leave.
  689. return;
  690. }
  691. /*
  692. * Create a parallel segment from merging returned and thrown.
  693. * This segment will leave at the end of this finally block.
  694. */
  695. const segments = forkContext.makeNext(-1, -1);
  696. for (let i = 0; i < forkContext.count; ++i) {
  697. const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]];
  698. for (let j = 0; j < returned.segmentsList.length; ++j) {
  699. prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]);
  700. }
  701. for (let j = 0; j < thrown.segmentsList.length; ++j) {
  702. prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]);
  703. }
  704. segments.push(
  705. CodePathSegment.newNext(
  706. this.idGenerator.next(),
  707. prevSegsOfLeavingSegment
  708. )
  709. );
  710. }
  711. this.pushForkContext(true);
  712. this.forkContext.add(segments);
  713. }
  714. /**
  715. * Makes a code path segment from the first throwable node to the `catch`
  716. * block or the `finally` block.
  717. * @returns {void}
  718. */
  719. makeFirstThrowablePathInTryBlock() {
  720. const forkContext = this.forkContext;
  721. if (!forkContext.reachable) {
  722. return;
  723. }
  724. const context = getThrowContext(this);
  725. if (context === this ||
  726. context.position !== "try" ||
  727. !context.thrownForkContext.empty
  728. ) {
  729. return;
  730. }
  731. context.thrownForkContext.add(forkContext.head);
  732. forkContext.replaceHead(forkContext.makeNext(-1, -1));
  733. }
  734. //--------------------------------------------------------------------------
  735. // Loop Statements
  736. //--------------------------------------------------------------------------
  737. /**
  738. * Creates a context object of a loop statement and stacks it.
  739. * @param {string} type The type of the node which was triggered. One of
  740. * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`,
  741. * and `ForStatement`.
  742. * @param {string|null} label A label of the node which was triggered.
  743. * @returns {void}
  744. */
  745. pushLoopContext(type, label) {
  746. const forkContext = this.forkContext;
  747. const breakContext = this.pushBreakContext(true, label);
  748. switch (type) {
  749. case "WhileStatement":
  750. this.pushChoiceContext("loop", false);
  751. this.loopContext = {
  752. upper: this.loopContext,
  753. type,
  754. label,
  755. test: void 0,
  756. continueDestSegments: null,
  757. brokenForkContext: breakContext.brokenForkContext
  758. };
  759. break;
  760. case "DoWhileStatement":
  761. this.pushChoiceContext("loop", false);
  762. this.loopContext = {
  763. upper: this.loopContext,
  764. type,
  765. label,
  766. test: void 0,
  767. entrySegments: null,
  768. continueForkContext: ForkContext.newEmpty(forkContext),
  769. brokenForkContext: breakContext.brokenForkContext
  770. };
  771. break;
  772. case "ForStatement":
  773. this.pushChoiceContext("loop", false);
  774. this.loopContext = {
  775. upper: this.loopContext,
  776. type,
  777. label,
  778. test: void 0,
  779. endOfInitSegments: null,
  780. testSegments: null,
  781. endOfTestSegments: null,
  782. updateSegments: null,
  783. endOfUpdateSegments: null,
  784. continueDestSegments: null,
  785. brokenForkContext: breakContext.brokenForkContext
  786. };
  787. break;
  788. case "ForInStatement":
  789. case "ForOfStatement":
  790. this.loopContext = {
  791. upper: this.loopContext,
  792. type,
  793. label,
  794. prevSegments: null,
  795. leftSegments: null,
  796. endOfLeftSegments: null,
  797. continueDestSegments: null,
  798. brokenForkContext: breakContext.brokenForkContext
  799. };
  800. break;
  801. /* istanbul ignore next */
  802. default:
  803. throw new Error(`unknown type: "${type}"`);
  804. }
  805. }
  806. /**
  807. * Pops the last context of a loop statement and finalizes it.
  808. * @returns {void}
  809. */
  810. popLoopContext() {
  811. const context = this.loopContext;
  812. this.loopContext = context.upper;
  813. const forkContext = this.forkContext;
  814. const brokenForkContext = this.popBreakContext().brokenForkContext;
  815. // Creates a looped path.
  816. switch (context.type) {
  817. case "WhileStatement":
  818. case "ForStatement":
  819. this.popChoiceContext();
  820. makeLooped(
  821. this,
  822. forkContext.head,
  823. context.continueDestSegments
  824. );
  825. break;
  826. case "DoWhileStatement": {
  827. const choiceContext = this.popChoiceContext();
  828. if (!choiceContext.processed) {
  829. choiceContext.trueForkContext.add(forkContext.head);
  830. choiceContext.falseForkContext.add(forkContext.head);
  831. }
  832. if (context.test !== true) {
  833. brokenForkContext.addAll(choiceContext.falseForkContext);
  834. }
  835. // `true` paths go to looping.
  836. const segmentsList = choiceContext.trueForkContext.segmentsList;
  837. for (let i = 0; i < segmentsList.length; ++i) {
  838. makeLooped(
  839. this,
  840. segmentsList[i],
  841. context.entrySegments
  842. );
  843. }
  844. break;
  845. }
  846. case "ForInStatement":
  847. case "ForOfStatement":
  848. brokenForkContext.add(forkContext.head);
  849. makeLooped(
  850. this,
  851. forkContext.head,
  852. context.leftSegments
  853. );
  854. break;
  855. /* istanbul ignore next */
  856. default:
  857. throw new Error("unreachable");
  858. }
  859. // Go next.
  860. if (brokenForkContext.empty) {
  861. forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
  862. } else {
  863. forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
  864. }
  865. }
  866. /**
  867. * Makes a code path segment for the test part of a WhileStatement.
  868. * @param {boolean|undefined} test The test value (only when constant).
  869. * @returns {void}
  870. */
  871. makeWhileTest(test) {
  872. const context = this.loopContext;
  873. const forkContext = this.forkContext;
  874. const testSegments = forkContext.makeNext(0, -1);
  875. // Update state.
  876. context.test = test;
  877. context.continueDestSegments = testSegments;
  878. forkContext.replaceHead(testSegments);
  879. }
  880. /**
  881. * Makes a code path segment for the body part of a WhileStatement.
  882. * @returns {void}
  883. */
  884. makeWhileBody() {
  885. const context = this.loopContext;
  886. const choiceContext = this.choiceContext;
  887. const forkContext = this.forkContext;
  888. if (!choiceContext.processed) {
  889. choiceContext.trueForkContext.add(forkContext.head);
  890. choiceContext.falseForkContext.add(forkContext.head);
  891. }
  892. // Update state.
  893. if (context.test !== true) {
  894. context.brokenForkContext.addAll(choiceContext.falseForkContext);
  895. }
  896. forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1));
  897. }
  898. /**
  899. * Makes a code path segment for the body part of a DoWhileStatement.
  900. * @returns {void}
  901. */
  902. makeDoWhileBody() {
  903. const context = this.loopContext;
  904. const forkContext = this.forkContext;
  905. const bodySegments = forkContext.makeNext(-1, -1);
  906. // Update state.
  907. context.entrySegments = bodySegments;
  908. forkContext.replaceHead(bodySegments);
  909. }
  910. /**
  911. * Makes a code path segment for the test part of a DoWhileStatement.
  912. * @param {boolean|undefined} test The test value (only when constant).
  913. * @returns {void}
  914. */
  915. makeDoWhileTest(test) {
  916. const context = this.loopContext;
  917. const forkContext = this.forkContext;
  918. context.test = test;
  919. // Creates paths of `continue` statements.
  920. if (!context.continueForkContext.empty) {
  921. context.continueForkContext.add(forkContext.head);
  922. const testSegments = context.continueForkContext.makeNext(0, -1);
  923. forkContext.replaceHead(testSegments);
  924. }
  925. }
  926. /**
  927. * Makes a code path segment for the test part of a ForStatement.
  928. * @param {boolean|undefined} test The test value (only when constant).
  929. * @returns {void}
  930. */
  931. makeForTest(test) {
  932. const context = this.loopContext;
  933. const forkContext = this.forkContext;
  934. const endOfInitSegments = forkContext.head;
  935. const testSegments = forkContext.makeNext(-1, -1);
  936. // Update state.
  937. context.test = test;
  938. context.endOfInitSegments = endOfInitSegments;
  939. context.continueDestSegments = context.testSegments = testSegments;
  940. forkContext.replaceHead(testSegments);
  941. }
  942. /**
  943. * Makes a code path segment for the update part of a ForStatement.
  944. * @returns {void}
  945. */
  946. makeForUpdate() {
  947. const context = this.loopContext;
  948. const choiceContext = this.choiceContext;
  949. const forkContext = this.forkContext;
  950. // Make the next paths of the test.
  951. if (context.testSegments) {
  952. finalizeTestSegmentsOfFor(
  953. context,
  954. choiceContext,
  955. forkContext.head
  956. );
  957. } else {
  958. context.endOfInitSegments = forkContext.head;
  959. }
  960. // Update state.
  961. const updateSegments = forkContext.makeDisconnected(-1, -1);
  962. context.continueDestSegments = context.updateSegments = updateSegments;
  963. forkContext.replaceHead(updateSegments);
  964. }
  965. /**
  966. * Makes a code path segment for the body part of a ForStatement.
  967. * @returns {void}
  968. */
  969. makeForBody() {
  970. const context = this.loopContext;
  971. const choiceContext = this.choiceContext;
  972. const forkContext = this.forkContext;
  973. // Update state.
  974. if (context.updateSegments) {
  975. context.endOfUpdateSegments = forkContext.head;
  976. // `update` -> `test`
  977. if (context.testSegments) {
  978. makeLooped(
  979. this,
  980. context.endOfUpdateSegments,
  981. context.testSegments
  982. );
  983. }
  984. } else if (context.testSegments) {
  985. finalizeTestSegmentsOfFor(
  986. context,
  987. choiceContext,
  988. forkContext.head
  989. );
  990. } else {
  991. context.endOfInitSegments = forkContext.head;
  992. }
  993. let bodySegments = context.endOfTestSegments;
  994. if (!bodySegments) {
  995. /*
  996. * If there is not the `test` part, the `body` path comes from the
  997. * `init` part and the `update` part.
  998. */
  999. const prevForkContext = ForkContext.newEmpty(forkContext);
  1000. prevForkContext.add(context.endOfInitSegments);
  1001. if (context.endOfUpdateSegments) {
  1002. prevForkContext.add(context.endOfUpdateSegments);
  1003. }
  1004. bodySegments = prevForkContext.makeNext(0, -1);
  1005. }
  1006. context.continueDestSegments = context.continueDestSegments || bodySegments;
  1007. forkContext.replaceHead(bodySegments);
  1008. }
  1009. /**
  1010. * Makes a code path segment for the left part of a ForInStatement and a
  1011. * ForOfStatement.
  1012. * @returns {void}
  1013. */
  1014. makeForInOfLeft() {
  1015. const context = this.loopContext;
  1016. const forkContext = this.forkContext;
  1017. const leftSegments = forkContext.makeDisconnected(-1, -1);
  1018. // Update state.
  1019. context.prevSegments = forkContext.head;
  1020. context.leftSegments = context.continueDestSegments = leftSegments;
  1021. forkContext.replaceHead(leftSegments);
  1022. }
  1023. /**
  1024. * Makes a code path segment for the right part of a ForInStatement and a
  1025. * ForOfStatement.
  1026. * @returns {void}
  1027. */
  1028. makeForInOfRight() {
  1029. const context = this.loopContext;
  1030. const forkContext = this.forkContext;
  1031. const temp = ForkContext.newEmpty(forkContext);
  1032. temp.add(context.prevSegments);
  1033. const rightSegments = temp.makeNext(-1, -1);
  1034. // Update state.
  1035. context.endOfLeftSegments = forkContext.head;
  1036. forkContext.replaceHead(rightSegments);
  1037. }
  1038. /**
  1039. * Makes a code path segment for the body part of a ForInStatement and a
  1040. * ForOfStatement.
  1041. * @returns {void}
  1042. */
  1043. makeForInOfBody() {
  1044. const context = this.loopContext;
  1045. const forkContext = this.forkContext;
  1046. const temp = ForkContext.newEmpty(forkContext);
  1047. temp.add(context.endOfLeftSegments);
  1048. const bodySegments = temp.makeNext(-1, -1);
  1049. // Make a path: `right` -> `left`.
  1050. makeLooped(this, forkContext.head, context.leftSegments);
  1051. // Update state.
  1052. context.brokenForkContext.add(forkContext.head);
  1053. forkContext.replaceHead(bodySegments);
  1054. }
  1055. //--------------------------------------------------------------------------
  1056. // Control Statements
  1057. //--------------------------------------------------------------------------
  1058. /**
  1059. * Creates new context for BreakStatement.
  1060. * @param {boolean} breakable The flag to indicate it can break by
  1061. * an unlabeled BreakStatement.
  1062. * @param {string|null} label The label of this context.
  1063. * @returns {Object} The new context.
  1064. */
  1065. pushBreakContext(breakable, label) {
  1066. this.breakContext = {
  1067. upper: this.breakContext,
  1068. breakable,
  1069. label,
  1070. brokenForkContext: ForkContext.newEmpty(this.forkContext)
  1071. };
  1072. return this.breakContext;
  1073. }
  1074. /**
  1075. * Removes the top item of the break context stack.
  1076. * @returns {Object} The removed context.
  1077. */
  1078. popBreakContext() {
  1079. const context = this.breakContext;
  1080. const forkContext = this.forkContext;
  1081. this.breakContext = context.upper;
  1082. // Process this context here for other than switches and loops.
  1083. if (!context.breakable) {
  1084. const brokenForkContext = context.brokenForkContext;
  1085. if (!brokenForkContext.empty) {
  1086. brokenForkContext.add(forkContext.head);
  1087. forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
  1088. }
  1089. }
  1090. return context;
  1091. }
  1092. /**
  1093. * Makes a path for a `break` statement.
  1094. *
  1095. * It registers the head segment to a context of `break`.
  1096. * It makes new unreachable segment, then it set the head with the segment.
  1097. * @param {string} label A label of the break statement.
  1098. * @returns {void}
  1099. */
  1100. makeBreak(label) {
  1101. const forkContext = this.forkContext;
  1102. if (!forkContext.reachable) {
  1103. return;
  1104. }
  1105. const context = getBreakContext(this, label);
  1106. /* istanbul ignore else: foolproof (syntax error) */
  1107. if (context) {
  1108. context.brokenForkContext.add(forkContext.head);
  1109. }
  1110. forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
  1111. }
  1112. /**
  1113. * Makes a path for a `continue` statement.
  1114. *
  1115. * It makes a looping path.
  1116. * It makes new unreachable segment, then it set the head with the segment.
  1117. * @param {string} label A label of the continue statement.
  1118. * @returns {void}
  1119. */
  1120. makeContinue(label) {
  1121. const forkContext = this.forkContext;
  1122. if (!forkContext.reachable) {
  1123. return;
  1124. }
  1125. const context = getContinueContext(this, label);
  1126. /* istanbul ignore else: foolproof (syntax error) */
  1127. if (context) {
  1128. if (context.continueDestSegments) {
  1129. makeLooped(this, forkContext.head, context.continueDestSegments);
  1130. // If the context is a for-in/of loop, this effects a break also.
  1131. if (context.type === "ForInStatement" ||
  1132. context.type === "ForOfStatement"
  1133. ) {
  1134. context.brokenForkContext.add(forkContext.head);
  1135. }
  1136. } else {
  1137. context.continueForkContext.add(forkContext.head);
  1138. }
  1139. }
  1140. forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
  1141. }
  1142. /**
  1143. * Makes a path for a `return` statement.
  1144. *
  1145. * It registers the head segment to a context of `return`.
  1146. * It makes new unreachable segment, then it set the head with the segment.
  1147. * @returns {void}
  1148. */
  1149. makeReturn() {
  1150. const forkContext = this.forkContext;
  1151. if (forkContext.reachable) {
  1152. getReturnContext(this).returnedForkContext.add(forkContext.head);
  1153. forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
  1154. }
  1155. }
  1156. /**
  1157. * Makes a path for a `throw` statement.
  1158. *
  1159. * It registers the head segment to a context of `throw`.
  1160. * It makes new unreachable segment, then it set the head with the segment.
  1161. * @returns {void}
  1162. */
  1163. makeThrow() {
  1164. const forkContext = this.forkContext;
  1165. if (forkContext.reachable) {
  1166. getThrowContext(this).thrownForkContext.add(forkContext.head);
  1167. forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
  1168. }
  1169. }
  1170. /**
  1171. * Makes the final path.
  1172. * @returns {void}
  1173. */
  1174. makeFinal() {
  1175. const segments = this.currentSegments;
  1176. if (segments.length > 0 && segments[0].reachable) {
  1177. this.returnedForkContext.add(segments);
  1178. }
  1179. }
  1180. }
  1181. module.exports = CodePathState;