]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/linter/code-path-analysis/code-path-state.js
import 8.3.0 source
[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 /**
223 * @param {IdGenerator} idGenerator An id generator to generate id for code
224 * path segments.
225 * @param {Function} onLooped A callback function to notify looping.
226 */
227 constructor(idGenerator, onLooped) {
228 this.idGenerator = idGenerator;
229 this.notifyLooped = onLooped;
230 this.forkContext = ForkContext.newRoot(idGenerator);
231 this.choiceContext = null;
232 this.switchContext = null;
233 this.tryContext = null;
234 this.loopContext = null;
235 this.breakContext = null;
236 this.chainContext = 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, AssignmentExpression (logical assignments only),
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 or AssignmentExpression's, this is `"&&"` or `"||"` 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 * @throws {Error} (Unreachable.)
363 * @returns {ChoiceContext} The popped context.
364 */
365 popChoiceContext() {
366 const context = this.choiceContext;
367
368 this.choiceContext = context.upper;
369
370 const forkContext = this.forkContext;
371 const headSegments = forkContext.head;
372
373 switch (context.kind) {
374 case "&&":
375 case "||":
376 case "??":
377
378 /*
379 * If any result were not transferred from child contexts,
380 * this sets the head segments to both cases.
381 * The head segments are the path of the right-hand operand.
382 */
383 if (!context.processed) {
384 context.trueForkContext.add(headSegments);
385 context.falseForkContext.add(headSegments);
386 context.qqForkContext.add(headSegments);
387 }
388
389 /*
390 * Transfers results to upper context if this context is in
391 * test chunk.
392 */
393 if (context.isForkingAsResult) {
394 const parentContext = this.choiceContext;
395
396 parentContext.trueForkContext.addAll(context.trueForkContext);
397 parentContext.falseForkContext.addAll(context.falseForkContext);
398 parentContext.qqForkContext.addAll(context.qqForkContext);
399 parentContext.processed = true;
400
401 return context;
402 }
403
404 break;
405
406 case "test":
407 if (!context.processed) {
408
409 /*
410 * The head segments are the path of the `if` block here.
411 * Updates the `true` path with the end of the `if` block.
412 */
413 context.trueForkContext.clear();
414 context.trueForkContext.add(headSegments);
415 } else {
416
417 /*
418 * The head segments are the path of the `else` block here.
419 * Updates the `false` path with the end of the `else`
420 * block.
421 */
422 context.falseForkContext.clear();
423 context.falseForkContext.add(headSegments);
424 }
425
426 break;
427
428 case "loop":
429
430 /*
431 * Loops are addressed in popLoopContext().
432 * This is called from popLoopContext().
433 */
434 return context;
435
436 /* istanbul ignore next */
437 default:
438 throw new Error("unreachable");
439 }
440
441 // Merges all paths.
442 const prevForkContext = context.trueForkContext;
443
444 prevForkContext.addAll(context.falseForkContext);
445 forkContext.replaceHead(prevForkContext.makeNext(0, -1));
446
447 return context;
448 }
449
450 /**
451 * Makes a code path segment of the right-hand operand of a logical
452 * expression.
453 * @throws {Error} (Unreachable.)
454 * @returns {void}
455 */
456 makeLogicalRight() {
457 const context = this.choiceContext;
458 const forkContext = this.forkContext;
459
460 if (context.processed) {
461
462 /*
463 * This got segments already from the child choice context.
464 * Creates the next path from own true/false fork context.
465 */
466 let prevForkContext;
467
468 switch (context.kind) {
469 case "&&": // if true then go to the right-hand side.
470 prevForkContext = context.trueForkContext;
471 break;
472 case "||": // if false then go to the right-hand side.
473 prevForkContext = context.falseForkContext;
474 break;
475 case "??": // Both true/false can short-circuit, so needs the third path to go to the right-hand side. That's qqForkContext.
476 prevForkContext = context.qqForkContext;
477 break;
478 default:
479 throw new Error("unreachable");
480 }
481
482 forkContext.replaceHead(prevForkContext.makeNext(0, -1));
483 prevForkContext.clear();
484 context.processed = false;
485 } else {
486
487 /*
488 * This did not get segments from the child choice context.
489 * So addresses the head segments.
490 * The head segments are the path of the left-hand operand.
491 */
492 switch (context.kind) {
493 case "&&": // the false path can short-circuit.
494 context.falseForkContext.add(forkContext.head);
495 break;
496 case "||": // the true path can short-circuit.
497 context.trueForkContext.add(forkContext.head);
498 break;
499 case "??": // both can short-circuit.
500 context.trueForkContext.add(forkContext.head);
501 context.falseForkContext.add(forkContext.head);
502 break;
503 default:
504 throw new Error("unreachable");
505 }
506
507 forkContext.replaceHead(forkContext.makeNext(-1, -1));
508 }
509 }
510
511 /**
512 * Makes a code path segment of the `if` block.
513 * @returns {void}
514 */
515 makeIfConsequent() {
516 const context = this.choiceContext;
517 const forkContext = this.forkContext;
518
519 /*
520 * If any result were not transferred from child contexts,
521 * this sets the head segments to both cases.
522 * The head segments are the path of the test expression.
523 */
524 if (!context.processed) {
525 context.trueForkContext.add(forkContext.head);
526 context.falseForkContext.add(forkContext.head);
527 context.qqForkContext.add(forkContext.head);
528 }
529
530 context.processed = false;
531
532 // Creates new path from the `true` case.
533 forkContext.replaceHead(
534 context.trueForkContext.makeNext(0, -1)
535 );
536 }
537
538 /**
539 * Makes a code path segment of the `else` block.
540 * @returns {void}
541 */
542 makeIfAlternate() {
543 const context = this.choiceContext;
544 const forkContext = this.forkContext;
545
546 /*
547 * The head segments are the path of the `if` block.
548 * Updates the `true` path with the end of the `if` block.
549 */
550 context.trueForkContext.clear();
551 context.trueForkContext.add(forkContext.head);
552 context.processed = true;
553
554 // Creates new path from the `false` case.
555 forkContext.replaceHead(
556 context.falseForkContext.makeNext(0, -1)
557 );
558 }
559
560 //--------------------------------------------------------------------------
561 // ChainExpression
562 //--------------------------------------------------------------------------
563
564 /**
565 * Push a new `ChainExpression` context to the stack.
566 * This method is called on entering to each `ChainExpression` node.
567 * This context is used to count forking in the optional chain then merge them on the exiting from the `ChainExpression` node.
568 * @returns {void}
569 */
570 pushChainContext() {
571 this.chainContext = {
572 upper: this.chainContext,
573 countChoiceContexts: 0
574 };
575 }
576
577 /**
578 * Pop a `ChainExpression` context from the stack.
579 * This method is called on exiting from each `ChainExpression` node.
580 * This merges all forks of the last optional chaining.
581 * @returns {void}
582 */
583 popChainContext() {
584 const context = this.chainContext;
585
586 this.chainContext = context.upper;
587
588 // pop all choice contexts of this.
589 for (let i = context.countChoiceContexts; i > 0; --i) {
590 this.popChoiceContext();
591 }
592 }
593
594 /**
595 * Create a choice context for optional access.
596 * This method is called on entering to each `(Call|Member)Expression[optional=true]` node.
597 * This creates a choice context as similar to `LogicalExpression[operator="??"]` node.
598 * @returns {void}
599 */
600 makeOptionalNode() {
601 if (this.chainContext) {
602 this.chainContext.countChoiceContexts += 1;
603 this.pushChoiceContext("??", false);
604 }
605 }
606
607 /**
608 * Create a fork.
609 * This method is called on entering to the `arguments|property` property of each `(Call|Member)Expression` node.
610 * @returns {void}
611 */
612 makeOptionalRight() {
613 if (this.chainContext) {
614 this.makeLogicalRight();
615 }
616 }
617
618 //--------------------------------------------------------------------------
619 // SwitchStatement
620 //--------------------------------------------------------------------------
621
622 /**
623 * Creates a context object of SwitchStatement and stacks it.
624 * @param {boolean} hasCase `true` if the switch statement has one or more
625 * case parts.
626 * @param {string|null} label The label text.
627 * @returns {void}
628 */
629 pushSwitchContext(hasCase, label) {
630 this.switchContext = {
631 upper: this.switchContext,
632 hasCase,
633 defaultSegments: null,
634 defaultBodySegments: null,
635 foundDefault: false,
636 lastIsDefault: false,
637 countForks: 0
638 };
639
640 this.pushBreakContext(true, label);
641 }
642
643 /**
644 * Pops the last context of SwitchStatement and finalizes it.
645 *
646 * - Disposes all forking stack for `case` and `default`.
647 * - Creates the next code path segment from `context.brokenForkContext`.
648 * - If the last `SwitchCase` node is not a `default` part, creates a path
649 * to the `default` body.
650 * @returns {void}
651 */
652 popSwitchContext() {
653 const context = this.switchContext;
654
655 this.switchContext = context.upper;
656
657 const forkContext = this.forkContext;
658 const brokenForkContext = this.popBreakContext().brokenForkContext;
659
660 if (context.countForks === 0) {
661
662 /*
663 * When there is only one `default` chunk and there is one or more
664 * `break` statements, even if forks are nothing, it needs to merge
665 * those.
666 */
667 if (!brokenForkContext.empty) {
668 brokenForkContext.add(forkContext.makeNext(-1, -1));
669 forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
670 }
671
672 return;
673 }
674
675 const lastSegments = forkContext.head;
676
677 this.forkBypassPath();
678 const lastCaseSegments = forkContext.head;
679
680 /*
681 * `brokenForkContext` is used to make the next segment.
682 * It must add the last segment into `brokenForkContext`.
683 */
684 brokenForkContext.add(lastSegments);
685
686 /*
687 * A path which is failed in all case test should be connected to path
688 * of `default` chunk.
689 */
690 if (!context.lastIsDefault) {
691 if (context.defaultBodySegments) {
692
693 /*
694 * Remove a link from `default` label to its chunk.
695 * It's false route.
696 */
697 removeConnection(context.defaultSegments, context.defaultBodySegments);
698 makeLooped(this, lastCaseSegments, context.defaultBodySegments);
699 } else {
700
701 /*
702 * It handles the last case body as broken if `default` chunk
703 * does not exist.
704 */
705 brokenForkContext.add(lastCaseSegments);
706 }
707 }
708
709 // Pops the segment context stack until the entry segment.
710 for (let i = 0; i < context.countForks; ++i) {
711 this.forkContext = this.forkContext.upper;
712 }
713
714 /*
715 * Creates a path from all brokenForkContext paths.
716 * This is a path after switch statement.
717 */
718 this.forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
719 }
720
721 /**
722 * Makes a code path segment for a `SwitchCase` node.
723 * @param {boolean} isEmpty `true` if the body is empty.
724 * @param {boolean} isDefault `true` if the body is the default case.
725 * @returns {void}
726 */
727 makeSwitchCaseBody(isEmpty, isDefault) {
728 const context = this.switchContext;
729
730 if (!context.hasCase) {
731 return;
732 }
733
734 /*
735 * Merge forks.
736 * The parent fork context has two segments.
737 * Those are from the current case and the body of the previous case.
738 */
739 const parentForkContext = this.forkContext;
740 const forkContext = this.pushForkContext();
741
742 forkContext.add(parentForkContext.makeNext(0, -1));
743
744 /*
745 * Save `default` chunk info.
746 * If the `default` label is not at the last, we must make a path from
747 * the last `case` to the `default` chunk.
748 */
749 if (isDefault) {
750 context.defaultSegments = parentForkContext.head;
751 if (isEmpty) {
752 context.foundDefault = true;
753 } else {
754 context.defaultBodySegments = forkContext.head;
755 }
756 } else {
757 if (!isEmpty && context.foundDefault) {
758 context.foundDefault = false;
759 context.defaultBodySegments = forkContext.head;
760 }
761 }
762
763 context.lastIsDefault = isDefault;
764 context.countForks += 1;
765 }
766
767 //--------------------------------------------------------------------------
768 // TryStatement
769 //--------------------------------------------------------------------------
770
771 /**
772 * Creates a context object of TryStatement and stacks it.
773 * @param {boolean} hasFinalizer `true` if the try statement has a
774 * `finally` block.
775 * @returns {void}
776 */
777 pushTryContext(hasFinalizer) {
778 this.tryContext = {
779 upper: this.tryContext,
780 position: "try",
781 hasFinalizer,
782
783 returnedForkContext: hasFinalizer
784 ? ForkContext.newEmpty(this.forkContext)
785 : null,
786
787 thrownForkContext: ForkContext.newEmpty(this.forkContext),
788 lastOfTryIsReachable: false,
789 lastOfCatchIsReachable: false
790 };
791 }
792
793 /**
794 * Pops the last context of TryStatement and finalizes it.
795 * @returns {void}
796 */
797 popTryContext() {
798 const context = this.tryContext;
799
800 this.tryContext = context.upper;
801
802 if (context.position === "catch") {
803
804 // Merges two paths from the `try` block and `catch` block merely.
805 this.popForkContext();
806 return;
807 }
808
809 /*
810 * The following process is executed only when there is the `finally`
811 * block.
812 */
813
814 const returned = context.returnedForkContext;
815 const thrown = context.thrownForkContext;
816
817 if (returned.empty && thrown.empty) {
818 return;
819 }
820
821 // Separate head to normal paths and leaving paths.
822 const headSegments = this.forkContext.head;
823
824 this.forkContext = this.forkContext.upper;
825 const normalSegments = headSegments.slice(0, headSegments.length / 2 | 0);
826 const leavingSegments = headSegments.slice(headSegments.length / 2 | 0);
827
828 // Forwards the leaving path to upper contexts.
829 if (!returned.empty) {
830 getReturnContext(this).returnedForkContext.add(leavingSegments);
831 }
832 if (!thrown.empty) {
833 getThrowContext(this).thrownForkContext.add(leavingSegments);
834 }
835
836 // Sets the normal path as the next.
837 this.forkContext.replaceHead(normalSegments);
838
839 /*
840 * If both paths of the `try` block and the `catch` block are
841 * unreachable, the next path becomes unreachable as well.
842 */
843 if (!context.lastOfTryIsReachable && !context.lastOfCatchIsReachable) {
844 this.forkContext.makeUnreachable();
845 }
846 }
847
848 /**
849 * Makes a code path segment for a `catch` block.
850 * @returns {void}
851 */
852 makeCatchBlock() {
853 const context = this.tryContext;
854 const forkContext = this.forkContext;
855 const thrown = context.thrownForkContext;
856
857 // Update state.
858 context.position = "catch";
859 context.thrownForkContext = ForkContext.newEmpty(forkContext);
860 context.lastOfTryIsReachable = forkContext.reachable;
861
862 // Merge thrown paths.
863 thrown.add(forkContext.head);
864 const thrownSegments = thrown.makeNext(0, -1);
865
866 // Fork to a bypass and the merged thrown path.
867 this.pushForkContext();
868 this.forkBypassPath();
869 this.forkContext.add(thrownSegments);
870 }
871
872 /**
873 * Makes a code path segment for a `finally` block.
874 *
875 * In the `finally` block, parallel paths are created. The parallel paths
876 * are used as leaving-paths. The leaving-paths are paths from `return`
877 * statements and `throw` statements in a `try` block or a `catch` block.
878 * @returns {void}
879 */
880 makeFinallyBlock() {
881 const context = this.tryContext;
882 let forkContext = this.forkContext;
883 const returned = context.returnedForkContext;
884 const thrown = context.thrownForkContext;
885 const headOfLeavingSegments = forkContext.head;
886
887 // Update state.
888 if (context.position === "catch") {
889
890 // Merges two paths from the `try` block and `catch` block.
891 this.popForkContext();
892 forkContext = this.forkContext;
893
894 context.lastOfCatchIsReachable = forkContext.reachable;
895 } else {
896 context.lastOfTryIsReachable = forkContext.reachable;
897 }
898 context.position = "finally";
899
900 if (returned.empty && thrown.empty) {
901
902 // This path does not leave.
903 return;
904 }
905
906 /*
907 * Create a parallel segment from merging returned and thrown.
908 * This segment will leave at the end of this finally block.
909 */
910 const segments = forkContext.makeNext(-1, -1);
911
912 for (let i = 0; i < forkContext.count; ++i) {
913 const prevSegsOfLeavingSegment = [headOfLeavingSegments[i]];
914
915 for (let j = 0; j < returned.segmentsList.length; ++j) {
916 prevSegsOfLeavingSegment.push(returned.segmentsList[j][i]);
917 }
918 for (let j = 0; j < thrown.segmentsList.length; ++j) {
919 prevSegsOfLeavingSegment.push(thrown.segmentsList[j][i]);
920 }
921
922 segments.push(
923 CodePathSegment.newNext(
924 this.idGenerator.next(),
925 prevSegsOfLeavingSegment
926 )
927 );
928 }
929
930 this.pushForkContext(true);
931 this.forkContext.add(segments);
932 }
933
934 /**
935 * Makes a code path segment from the first throwable node to the `catch`
936 * block or the `finally` block.
937 * @returns {void}
938 */
939 makeFirstThrowablePathInTryBlock() {
940 const forkContext = this.forkContext;
941
942 if (!forkContext.reachable) {
943 return;
944 }
945
946 const context = getThrowContext(this);
947
948 if (context === this ||
949 context.position !== "try" ||
950 !context.thrownForkContext.empty
951 ) {
952 return;
953 }
954
955 context.thrownForkContext.add(forkContext.head);
956 forkContext.replaceHead(forkContext.makeNext(-1, -1));
957 }
958
959 //--------------------------------------------------------------------------
960 // Loop Statements
961 //--------------------------------------------------------------------------
962
963 /**
964 * Creates a context object of a loop statement and stacks it.
965 * @param {string} type The type of the node which was triggered. One of
966 * `WhileStatement`, `DoWhileStatement`, `ForStatement`, `ForInStatement`,
967 * and `ForStatement`.
968 * @param {string|null} label A label of the node which was triggered.
969 * @throws {Error} (Unreachable - unknown type.)
970 * @returns {void}
971 */
972 pushLoopContext(type, label) {
973 const forkContext = this.forkContext;
974 const breakContext = this.pushBreakContext(true, label);
975
976 switch (type) {
977 case "WhileStatement":
978 this.pushChoiceContext("loop", false);
979 this.loopContext = {
980 upper: this.loopContext,
981 type,
982 label,
983 test: void 0,
984 continueDestSegments: null,
985 brokenForkContext: breakContext.brokenForkContext
986 };
987 break;
988
989 case "DoWhileStatement":
990 this.pushChoiceContext("loop", false);
991 this.loopContext = {
992 upper: this.loopContext,
993 type,
994 label,
995 test: void 0,
996 entrySegments: null,
997 continueForkContext: ForkContext.newEmpty(forkContext),
998 brokenForkContext: breakContext.brokenForkContext
999 };
1000 break;
1001
1002 case "ForStatement":
1003 this.pushChoiceContext("loop", false);
1004 this.loopContext = {
1005 upper: this.loopContext,
1006 type,
1007 label,
1008 test: void 0,
1009 endOfInitSegments: null,
1010 testSegments: null,
1011 endOfTestSegments: null,
1012 updateSegments: null,
1013 endOfUpdateSegments: null,
1014 continueDestSegments: null,
1015 brokenForkContext: breakContext.brokenForkContext
1016 };
1017 break;
1018
1019 case "ForInStatement":
1020 case "ForOfStatement":
1021 this.loopContext = {
1022 upper: this.loopContext,
1023 type,
1024 label,
1025 prevSegments: null,
1026 leftSegments: null,
1027 endOfLeftSegments: null,
1028 continueDestSegments: null,
1029 brokenForkContext: breakContext.brokenForkContext
1030 };
1031 break;
1032
1033 /* istanbul ignore next */
1034 default:
1035 throw new Error(`unknown type: "${type}"`);
1036 }
1037 }
1038
1039 /**
1040 * Pops the last context of a loop statement and finalizes it.
1041 * @throws {Error} (Unreachable - unknown type.)
1042 * @returns {void}
1043 */
1044 popLoopContext() {
1045 const context = this.loopContext;
1046
1047 this.loopContext = context.upper;
1048
1049 const forkContext = this.forkContext;
1050 const brokenForkContext = this.popBreakContext().brokenForkContext;
1051
1052 // Creates a looped path.
1053 switch (context.type) {
1054 case "WhileStatement":
1055 case "ForStatement":
1056 this.popChoiceContext();
1057 makeLooped(
1058 this,
1059 forkContext.head,
1060 context.continueDestSegments
1061 );
1062 break;
1063
1064 case "DoWhileStatement": {
1065 const choiceContext = this.popChoiceContext();
1066
1067 if (!choiceContext.processed) {
1068 choiceContext.trueForkContext.add(forkContext.head);
1069 choiceContext.falseForkContext.add(forkContext.head);
1070 }
1071 if (context.test !== true) {
1072 brokenForkContext.addAll(choiceContext.falseForkContext);
1073 }
1074
1075 // `true` paths go to looping.
1076 const segmentsList = choiceContext.trueForkContext.segmentsList;
1077
1078 for (let i = 0; i < segmentsList.length; ++i) {
1079 makeLooped(
1080 this,
1081 segmentsList[i],
1082 context.entrySegments
1083 );
1084 }
1085 break;
1086 }
1087
1088 case "ForInStatement":
1089 case "ForOfStatement":
1090 brokenForkContext.add(forkContext.head);
1091 makeLooped(
1092 this,
1093 forkContext.head,
1094 context.leftSegments
1095 );
1096 break;
1097
1098 /* istanbul ignore next */
1099 default:
1100 throw new Error("unreachable");
1101 }
1102
1103 // Go next.
1104 if (brokenForkContext.empty) {
1105 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
1106 } else {
1107 forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
1108 }
1109 }
1110
1111 /**
1112 * Makes a code path segment for the test part of a WhileStatement.
1113 * @param {boolean|undefined} test The test value (only when constant).
1114 * @returns {void}
1115 */
1116 makeWhileTest(test) {
1117 const context = this.loopContext;
1118 const forkContext = this.forkContext;
1119 const testSegments = forkContext.makeNext(0, -1);
1120
1121 // Update state.
1122 context.test = test;
1123 context.continueDestSegments = testSegments;
1124 forkContext.replaceHead(testSegments);
1125 }
1126
1127 /**
1128 * Makes a code path segment for the body part of a WhileStatement.
1129 * @returns {void}
1130 */
1131 makeWhileBody() {
1132 const context = this.loopContext;
1133 const choiceContext = this.choiceContext;
1134 const forkContext = this.forkContext;
1135
1136 if (!choiceContext.processed) {
1137 choiceContext.trueForkContext.add(forkContext.head);
1138 choiceContext.falseForkContext.add(forkContext.head);
1139 }
1140
1141 // Update state.
1142 if (context.test !== true) {
1143 context.brokenForkContext.addAll(choiceContext.falseForkContext);
1144 }
1145 forkContext.replaceHead(choiceContext.trueForkContext.makeNext(0, -1));
1146 }
1147
1148 /**
1149 * Makes a code path segment for the body part of a DoWhileStatement.
1150 * @returns {void}
1151 */
1152 makeDoWhileBody() {
1153 const context = this.loopContext;
1154 const forkContext = this.forkContext;
1155 const bodySegments = forkContext.makeNext(-1, -1);
1156
1157 // Update state.
1158 context.entrySegments = bodySegments;
1159 forkContext.replaceHead(bodySegments);
1160 }
1161
1162 /**
1163 * Makes a code path segment for the test part of a DoWhileStatement.
1164 * @param {boolean|undefined} test The test value (only when constant).
1165 * @returns {void}
1166 */
1167 makeDoWhileTest(test) {
1168 const context = this.loopContext;
1169 const forkContext = this.forkContext;
1170
1171 context.test = test;
1172
1173 // Creates paths of `continue` statements.
1174 if (!context.continueForkContext.empty) {
1175 context.continueForkContext.add(forkContext.head);
1176 const testSegments = context.continueForkContext.makeNext(0, -1);
1177
1178 forkContext.replaceHead(testSegments);
1179 }
1180 }
1181
1182 /**
1183 * Makes a code path segment for the test part of a ForStatement.
1184 * @param {boolean|undefined} test The test value (only when constant).
1185 * @returns {void}
1186 */
1187 makeForTest(test) {
1188 const context = this.loopContext;
1189 const forkContext = this.forkContext;
1190 const endOfInitSegments = forkContext.head;
1191 const testSegments = forkContext.makeNext(-1, -1);
1192
1193 // Update state.
1194 context.test = test;
1195 context.endOfInitSegments = endOfInitSegments;
1196 context.continueDestSegments = context.testSegments = testSegments;
1197 forkContext.replaceHead(testSegments);
1198 }
1199
1200 /**
1201 * Makes a code path segment for the update part of a ForStatement.
1202 * @returns {void}
1203 */
1204 makeForUpdate() {
1205 const context = this.loopContext;
1206 const choiceContext = this.choiceContext;
1207 const forkContext = this.forkContext;
1208
1209 // Make the next paths of the test.
1210 if (context.testSegments) {
1211 finalizeTestSegmentsOfFor(
1212 context,
1213 choiceContext,
1214 forkContext.head
1215 );
1216 } else {
1217 context.endOfInitSegments = forkContext.head;
1218 }
1219
1220 // Update state.
1221 const updateSegments = forkContext.makeDisconnected(-1, -1);
1222
1223 context.continueDestSegments = context.updateSegments = updateSegments;
1224 forkContext.replaceHead(updateSegments);
1225 }
1226
1227 /**
1228 * Makes a code path segment for the body part of a ForStatement.
1229 * @returns {void}
1230 */
1231 makeForBody() {
1232 const context = this.loopContext;
1233 const choiceContext = this.choiceContext;
1234 const forkContext = this.forkContext;
1235
1236 // Update state.
1237 if (context.updateSegments) {
1238 context.endOfUpdateSegments = forkContext.head;
1239
1240 // `update` -> `test`
1241 if (context.testSegments) {
1242 makeLooped(
1243 this,
1244 context.endOfUpdateSegments,
1245 context.testSegments
1246 );
1247 }
1248 } else if (context.testSegments) {
1249 finalizeTestSegmentsOfFor(
1250 context,
1251 choiceContext,
1252 forkContext.head
1253 );
1254 } else {
1255 context.endOfInitSegments = forkContext.head;
1256 }
1257
1258 let bodySegments = context.endOfTestSegments;
1259
1260 if (!bodySegments) {
1261
1262 /*
1263 * If there is not the `test` part, the `body` path comes from the
1264 * `init` part and the `update` part.
1265 */
1266 const prevForkContext = ForkContext.newEmpty(forkContext);
1267
1268 prevForkContext.add(context.endOfInitSegments);
1269 if (context.endOfUpdateSegments) {
1270 prevForkContext.add(context.endOfUpdateSegments);
1271 }
1272
1273 bodySegments = prevForkContext.makeNext(0, -1);
1274 }
1275 context.continueDestSegments = context.continueDestSegments || bodySegments;
1276 forkContext.replaceHead(bodySegments);
1277 }
1278
1279 /**
1280 * Makes a code path segment for the left part of a ForInStatement and a
1281 * ForOfStatement.
1282 * @returns {void}
1283 */
1284 makeForInOfLeft() {
1285 const context = this.loopContext;
1286 const forkContext = this.forkContext;
1287 const leftSegments = forkContext.makeDisconnected(-1, -1);
1288
1289 // Update state.
1290 context.prevSegments = forkContext.head;
1291 context.leftSegments = context.continueDestSegments = leftSegments;
1292 forkContext.replaceHead(leftSegments);
1293 }
1294
1295 /**
1296 * Makes a code path segment for the right part of a ForInStatement and a
1297 * ForOfStatement.
1298 * @returns {void}
1299 */
1300 makeForInOfRight() {
1301 const context = this.loopContext;
1302 const forkContext = this.forkContext;
1303 const temp = ForkContext.newEmpty(forkContext);
1304
1305 temp.add(context.prevSegments);
1306 const rightSegments = temp.makeNext(-1, -1);
1307
1308 // Update state.
1309 context.endOfLeftSegments = forkContext.head;
1310 forkContext.replaceHead(rightSegments);
1311 }
1312
1313 /**
1314 * Makes a code path segment for the body part of a ForInStatement and a
1315 * ForOfStatement.
1316 * @returns {void}
1317 */
1318 makeForInOfBody() {
1319 const context = this.loopContext;
1320 const forkContext = this.forkContext;
1321 const temp = ForkContext.newEmpty(forkContext);
1322
1323 temp.add(context.endOfLeftSegments);
1324 const bodySegments = temp.makeNext(-1, -1);
1325
1326 // Make a path: `right` -> `left`.
1327 makeLooped(this, forkContext.head, context.leftSegments);
1328
1329 // Update state.
1330 context.brokenForkContext.add(forkContext.head);
1331 forkContext.replaceHead(bodySegments);
1332 }
1333
1334 //--------------------------------------------------------------------------
1335 // Control Statements
1336 //--------------------------------------------------------------------------
1337
1338 /**
1339 * Creates new context for BreakStatement.
1340 * @param {boolean} breakable The flag to indicate it can break by
1341 * an unlabeled BreakStatement.
1342 * @param {string|null} label The label of this context.
1343 * @returns {Object} The new context.
1344 */
1345 pushBreakContext(breakable, label) {
1346 this.breakContext = {
1347 upper: this.breakContext,
1348 breakable,
1349 label,
1350 brokenForkContext: ForkContext.newEmpty(this.forkContext)
1351 };
1352 return this.breakContext;
1353 }
1354
1355 /**
1356 * Removes the top item of the break context stack.
1357 * @returns {Object} The removed context.
1358 */
1359 popBreakContext() {
1360 const context = this.breakContext;
1361 const forkContext = this.forkContext;
1362
1363 this.breakContext = context.upper;
1364
1365 // Process this context here for other than switches and loops.
1366 if (!context.breakable) {
1367 const brokenForkContext = context.brokenForkContext;
1368
1369 if (!brokenForkContext.empty) {
1370 brokenForkContext.add(forkContext.head);
1371 forkContext.replaceHead(brokenForkContext.makeNext(0, -1));
1372 }
1373 }
1374
1375 return context;
1376 }
1377
1378 /**
1379 * Makes a path for a `break` statement.
1380 *
1381 * It registers the head segment to a context of `break`.
1382 * It makes new unreachable segment, then it set the head with the segment.
1383 * @param {string} label A label of the break statement.
1384 * @returns {void}
1385 */
1386 makeBreak(label) {
1387 const forkContext = this.forkContext;
1388
1389 if (!forkContext.reachable) {
1390 return;
1391 }
1392
1393 const context = getBreakContext(this, label);
1394
1395 /* istanbul ignore else: foolproof (syntax error) */
1396 if (context) {
1397 context.brokenForkContext.add(forkContext.head);
1398 }
1399
1400 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
1401 }
1402
1403 /**
1404 * Makes a path for a `continue` statement.
1405 *
1406 * It makes a looping path.
1407 * It makes new unreachable segment, then it set the head with the segment.
1408 * @param {string} label A label of the continue statement.
1409 * @returns {void}
1410 */
1411 makeContinue(label) {
1412 const forkContext = this.forkContext;
1413
1414 if (!forkContext.reachable) {
1415 return;
1416 }
1417
1418 const context = getContinueContext(this, label);
1419
1420 /* istanbul ignore else: foolproof (syntax error) */
1421 if (context) {
1422 if (context.continueDestSegments) {
1423 makeLooped(this, forkContext.head, context.continueDestSegments);
1424
1425 // If the context is a for-in/of loop, this effects a break also.
1426 if (context.type === "ForInStatement" ||
1427 context.type === "ForOfStatement"
1428 ) {
1429 context.brokenForkContext.add(forkContext.head);
1430 }
1431 } else {
1432 context.continueForkContext.add(forkContext.head);
1433 }
1434 }
1435 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
1436 }
1437
1438 /**
1439 * Makes a path for a `return` statement.
1440 *
1441 * It registers the head segment to a context of `return`.
1442 * It makes new unreachable segment, then it set the head with the segment.
1443 * @returns {void}
1444 */
1445 makeReturn() {
1446 const forkContext = this.forkContext;
1447
1448 if (forkContext.reachable) {
1449 getReturnContext(this).returnedForkContext.add(forkContext.head);
1450 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
1451 }
1452 }
1453
1454 /**
1455 * Makes a path for a `throw` statement.
1456 *
1457 * It registers the head segment to a context of `throw`.
1458 * It makes new unreachable segment, then it set the head with the segment.
1459 * @returns {void}
1460 */
1461 makeThrow() {
1462 const forkContext = this.forkContext;
1463
1464 if (forkContext.reachable) {
1465 getThrowContext(this).thrownForkContext.add(forkContext.head);
1466 forkContext.replaceHead(forkContext.makeUnreachable(-1, -1));
1467 }
1468 }
1469
1470 /**
1471 * Makes the final path.
1472 * @returns {void}
1473 */
1474 makeFinal() {
1475 const segments = this.currentSegments;
1476
1477 if (segments.length > 0 && segments[0].reachable) {
1478 this.returnedForkContext.add(segments);
1479 }
1480 }
1481 }
1482
1483 module.exports = CodePathState;