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