-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-path-state.js
More file actions
2348 lines (2015 loc) · 80.1 KB
/
Copy pathcode-path-state.js
File metadata and controls
2348 lines (2015 loc) · 80.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview A class to manage state of generating a code path.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const CodePathSegment = require("./code-path-segment"),
ForkContext = require("./fork-context");
//-----------------------------------------------------------------------------
// Contexts
//-----------------------------------------------------------------------------
/**
* Represents the context in which a `break` statement can be used.
*
* A `break` statement without a label is only valid in a few places in
* JavaScript: any type of loop or a `switch` statement. Otherwise, `break`
* without a label causes a syntax error. For these contexts, `breakable` is
* set to `true` to indicate that a `break` without a label is valid.
*
* However, a `break` statement with a label is also valid inside of a labeled
* statement. For example, this is valid:
*
* a : {
* break a;
* }
*
* The `breakable` property is set false for labeled statements to indicate
* that `break` without a label is invalid.
*/
class BreakContext {
/**
* Creates a new instance.
* @param {BreakContext} upperContext The previous `BreakContext`.
* @param {boolean} breakable Indicates if we are inside a statement where
* `break` without a label will exit the statement.
* @param {string|null} label The label for the statement.
* @param {ForkContext} forkContext The current fork context.
*/
constructor(upperContext, breakable, label, forkContext) {
/**
* The previous `BreakContext`
* @type {BreakContext}
*/
this.upper = upperContext;
/**
* Indicates if we are inside a statement where `break` without a label
* will exit the statement.
* @type {boolean}
*/
this.breakable = breakable;
/**
* The label associated with the statement.
* @type {string|null}
*/
this.label = label;
/**
* The fork context for the `break`.
* @type {ForkContext}
*/
this.brokenForkContext = ForkContext.newEmpty(forkContext);
}
}
/**
* Represents the context for `ChainExpression` nodes.
*/
class ChainContext {
/**
* Creates a new instance.
* @param {ChainContext} upperContext The previous `ChainContext`.
*/
constructor(upperContext) {
/**
* The previous `ChainContext`
* @type {ChainContext}
*/
this.upper = upperContext;
/**
* The number of choice contexts inside of the `ChainContext`.
* @type {number}
*/
this.choiceContextCount = 0;
}
}
/**
* Represents a choice in the code path.
*
* Choices are created by logical operators such as `&&`, loops, conditionals,
* and `if` statements. This is the point at which the code path has a choice of
* which direction to go.
*
* The result of a choice might be in the left (test) expression of another choice,
* and in that case, may create a new fork. For example, `a || b` is a choice
* but does not create a new fork because the result of the expression is
* not used as the test expression in another expression. In this case,
* `isForkingAsResult` is false. In the expression `a || b || c`, the `a || b`
* expression appears as the test expression for `|| c`, so the
* result of `a || b` creates a fork because execution may or may not
* continue to `|| c`. `isForkingAsResult` for `a || b` in this case is true
* while `isForkingAsResult` for `|| c` is false. (`isForkingAsResult` is always
* false for `if` statements, conditional expressions, and loops.)
*
* All of the choices except one (`??`) operate on a true/false fork, meaning if
* true go one way and if false go the other (tracked by `trueForkContext` and
* `falseForkContext`). The `??` operator doesn't operate on true/false because
* the left expression is evaluated to be nullish or not, so only if nullish do
* we fork to the right expression (tracked by `nullishForkContext`).
*/
class ChoiceContext {
/**
* Creates a new instance.
* @param {ChoiceContext} upperContext The previous `ChoiceContext`.
* @param {string} kind The kind of choice. If it's a logical or assignment expression, this
* is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or
* conditional expression, this is `"test"`; otherwise, this is `"loop"`.
* @param {boolean} isForkingAsResult Indicates if the result of the choice
* creates a fork.
* @param {ForkContext} forkContext The containing `ForkContext`.
*/
constructor(upperContext, kind, isForkingAsResult, forkContext) {
/**
* The previous `ChoiceContext`
* @type {ChoiceContext}
*/
this.upper = upperContext;
/**
* The kind of choice. If it's a logical or assignment expression, this
* is `"&&"` or `"||"` or `"??"`; if it's an `if` statement or
* conditional expression, this is `"test"`; otherwise, this is `"loop"`.
* @type {string}
*/
this.kind = kind;
/**
* Indicates if the result of the choice forks the code path.
* @type {boolean}
*/
this.isForkingAsResult = isForkingAsResult;
/**
* The fork context for the `true` path of the choice.
* @type {ForkContext}
*/
this.trueForkContext = ForkContext.newEmpty(forkContext);
/**
* The fork context for the `false` path of the choice.
* @type {ForkContext}
*/
this.falseForkContext = ForkContext.newEmpty(forkContext);
/**
* The fork context for when the choice result is `null` or `undefined`.
* @type {ForkContext}
*/
this.nullishForkContext = ForkContext.newEmpty(forkContext);
/**
* Indicates if any of `trueForkContext`, `falseForkContext`, or
* `nullishForkContext` have been updated with segments from a child context.
* @type {boolean}
*/
this.processed = false;
}
}
/**
* Base class for all loop contexts.
*/
class LoopContextBase {
/**
* Creates a new instance.
* @param {LoopContext|null} upperContext The previous `LoopContext`.
* @param {string} type The AST node's `type` for the loop.
* @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
* @param {BreakContext} breakContext The context for breaking the loop.
*/
constructor(upperContext, type, label, breakContext) {
/**
* The previous `LoopContext`.
* @type {LoopContext}
*/
this.upper = upperContext;
/**
* The AST node's `type` for the loop.
* @type {string}
*/
this.type = type;
/**
* The label for the loop from an enclosing `LabeledStatement`.
* @type {string|null}
*/
this.label = label;
/**
* The fork context for when `break` is encountered.
* @type {ForkContext}
*/
this.brokenForkContext = breakContext.brokenForkContext;
}
}
/**
* Represents the context for a `while` loop.
*/
class WhileLoopContext extends LoopContextBase {
/**
* Creates a new instance.
* @param {LoopContext|null} upperContext The previous `LoopContext`.
* @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
* @param {BreakContext} breakContext The context for breaking the loop.
*/
constructor(upperContext, label, breakContext) {
super(upperContext, "WhileStatement", label, breakContext);
/**
* The hardcoded literal boolean test condition for
* the loop. Used to catch infinite or skipped loops.
* @type {boolean|undefined}
*/
this.test = void 0;
/**
* The segments representing the test condition where `continue` will
* jump to. The test condition will typically have just one segment but
* it's possible for there to be more than one.
* @type {Array<CodePathSegment>|null}
*/
this.continueDestSegments = null;
}
}
/**
* Represents the context for a `do-while` loop.
*/
class DoWhileLoopContext extends LoopContextBase {
/**
* Creates a new instance.
* @param {LoopContext|null} upperContext The previous `LoopContext`.
* @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
* @param {BreakContext} breakContext The context for breaking the loop.
* @param {ForkContext} forkContext The enclosing fork context.
*/
constructor(upperContext, label, breakContext, forkContext) {
super(upperContext, "DoWhileStatement", label, breakContext);
/**
* The hardcoded literal boolean test condition for
* the loop. Used to catch infinite or skipped loops.
* @type {boolean|undefined}
*/
this.test = void 0;
/**
* The segments at the start of the loop body. This is the only loop
* where the test comes at the end, so the first iteration always
* happens and we need a reference to the first statements.
* @type {Array<CodePathSegment>|null}
*/
this.entrySegments = null;
/**
* The fork context to follow when a `continue` is found.
* @type {ForkContext}
*/
this.continueForkContext = ForkContext.newEmpty(forkContext);
}
}
/**
* Represents the context for a `for` loop.
*/
class ForLoopContext extends LoopContextBase {
/**
* Creates a new instance.
* @param {LoopContext|null} upperContext The previous `LoopContext`.
* @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
* @param {BreakContext} breakContext The context for breaking the loop.
*/
constructor(upperContext, label, breakContext) {
super(upperContext, "ForStatement", label, breakContext);
/**
* The hardcoded literal boolean test condition for
* the loop. Used to catch infinite or skipped loops.
* @type {boolean|undefined}
*/
this.test = void 0;
/**
* The end of the init expression. This may change during the lifetime
* of the instance as we traverse the loop because some loops don't have
* an init expression.
* @type {Array<CodePathSegment>|null}
*/
this.endOfInitSegments = null;
/**
* The start of the test expression. This may change during the lifetime
* of the instance as we traverse the loop because some loops don't have
* a test expression.
* @type {Array<CodePathSegment>|null}
*/
this.testSegments = null;
/**
* The end of the test expression. This may change during the lifetime
* of the instance as we traverse the loop because some loops don't have
* a test expression.
* @type {Array<CodePathSegment>|null}
*/
this.endOfTestSegments = null;
/**
* The start of the update expression. This may change during the lifetime
* of the instance as we traverse the loop because some loops don't have
* an update expression.
* @type {Array<CodePathSegment>|null}
*/
this.updateSegments = null;
/**
* The end of the update expresion. This may change during the lifetime
* of the instance as we traverse the loop because some loops don't have
* an update expression.
* @type {Array<CodePathSegment>|null}
*/
this.endOfUpdateSegments = null;
/**
* The segments representing the test condition where `continue` will
* jump to. The test condition will typically have just one segment but
* it's possible for there to be more than one. This may change during the
* lifetime of the instance as we traverse the loop because some loops
* don't have an update expression. When there is an update expression, this
* will end up pointing to that expression; otherwise it will end up pointing
* to the test expression.
* @type {Array<CodePathSegment>|null}
*/
this.continueDestSegments = null;
}
}
/**
* Represents the context for a `for-in` loop.
*
* Terminology:
* - "left" means the part of the loop to the left of the `in` keyword. For
* example, in `for (var x in y)`, the left is `var x`.
* - "right" means the part of the loop to the right of the `in` keyword. For
* example, in `for (var x in y)`, the right is `y`.
*/
class ForInLoopContext extends LoopContextBase {
/**
* Creates a new instance.
* @param {LoopContext|null} upperContext The previous `LoopContext`.
* @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
* @param {BreakContext} breakContext The context for breaking the loop.
*/
constructor(upperContext, label, breakContext) {
super(upperContext, "ForInStatement", label, breakContext);
/**
* The segments that came immediately before the start of the loop.
* This allows you to traverse backwards out of the loop into the
* surrounding code. This is necessary to evaluate the right expression
* correctly, as it must be evaluated in the same way as the left
* expression, but the pointer to these segments would otherwise be
* lost if not stored on the instance. Once the right expression has
* been evaluated, this property is no longer used.
* @type {Array<CodePathSegment>|null}
*/
this.prevSegments = null;
/**
* Segments representing the start of everything to the left of the
* `in` keyword. This can be used to move forward towards
* `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are
* effectively the head and tail of a doubly-linked list.
* @type {Array<CodePathSegment>|null}
*/
this.leftSegments = null;
/**
* Segments representing the end of everything to the left of the
* `in` keyword. This can be used to move backward towards `leftSegments`.
* `leftSegments` and `endOfLeftSegments` are effectively the head
* and tail of a doubly-linked list.
* @type {Array<CodePathSegment>|null}
*/
this.endOfLeftSegments = null;
/**
* The segments representing the left expression where `continue` will
* jump to. In `for-in` loops, `continue` must always re-execute the
* left expression each time through the loop. This contains the same
* segments as `leftSegments`, but is duplicated here so each loop
* context has the same property pointing to where `continue` should
* end up.
* @type {Array<CodePathSegment>|null}
*/
this.continueDestSegments = null;
}
}
/**
* Represents the context for a `for-of` loop.
*/
class ForOfLoopContext extends LoopContextBase {
/**
* Creates a new instance.
* @param {LoopContext|null} upperContext The previous `LoopContext`.
* @param {string|null} label The label for the loop from an enclosing `LabeledStatement`.
* @param {BreakContext} breakContext The context for breaking the loop.
*/
constructor(upperContext, label, breakContext) {
super(upperContext, "ForOfStatement", label, breakContext);
/**
* The segments that came immediately before the start of the loop.
* This allows you to traverse backwards out of the loop into the
* surrounding code. This is necessary to evaluate the right expression
* correctly, as it must be evaluated in the same way as the left
* expression, but the pointer to these segments would otherwise be
* lost if not stored on the instance. Once the right expression has
* been evaluated, this property is no longer used.
* @type {Array<CodePathSegment>|null}
*/
this.prevSegments = null;
/**
* Segments representing the start of everything to the left of the
* `of` keyword. This can be used to move forward towards
* `endOfLeftSegments`. `leftSegments` and `endOfLeftSegments` are
* effectively the head and tail of a doubly-linked list.
* @type {Array<CodePathSegment>|null}
*/
this.leftSegments = null;
/**
* Segments representing the end of everything to the left of the
* `of` keyword. This can be used to move backward towards `leftSegments`.
* `leftSegments` and `endOfLeftSegments` are effectively the head
* and tail of a doubly-linked list.
* @type {Array<CodePathSegment>|null}
*/
this.endOfLeftSegments = null;
/**
* The segments representing the left expression where `continue` will
* jump to. In `for-in` loops, `continue` must always re-execute the
* left expression each time through the loop. This contains the same
* segments as `leftSegments`, but is duplicated here so each loop
* context has the same property pointing to where `continue` should
* end up.
* @type {Array<CodePathSegment>|null}
*/
this.continueDestSegments = null;
}
}
/**
* Represents the context for any loop.
* @typedef {WhileLoopContext|DoWhileLoopContext|ForLoopContext|ForInLoopContext|ForOfLoopContext} LoopContext
*/
/**
* Represents the context for a `switch` statement.
*/
class SwitchContext {
/**
* Creates a new instance.
* @param {SwitchContext} upperContext The previous context.
* @param {boolean} hasCase Indicates if there is at least one `case` statement.
* `default` doesn't count.
*/
constructor(upperContext, hasCase) {
/**
* The previous context.
* @type {SwitchContext}
*/
this.upper = upperContext;
/**
* Indicates if there is at least one `case` statement. `default` doesn't count.
* @type {boolean}
*/
this.hasCase = hasCase;
/**
* The `default` keyword.
* @type {Array<CodePathSegment>|null}
*/
this.defaultSegments = null;
/**
* The default case body starting segments.
* @type {Array<CodePathSegment>|null}
*/
this.defaultBodySegments = null;
/**
* Indicates if a `default` case and is empty exists.
* @type {boolean}
*/
this.foundEmptyDefault = false;
/**
* Indicates that a `default` exists and is the last case.
* @type {boolean}
*/
this.lastIsDefault = false;
/**
* The number of fork contexts created. This is equivalent to the
* number of `case` statements plus a `default` statement (if present).
* @type {number}
*/
this.forkCount = 0;
}
}
/**
* Represents the context for a `try` statement.
*/
class TryContext {
/**
* Creates a new instance.
* @param {TryContext} upperContext The previous context.
* @param {boolean} hasFinalizer Indicates if the `try` statement has a
* `finally` block.
* @param {ForkContext} forkContext The enclosing fork context.
*/
constructor(upperContext, hasFinalizer, forkContext) {
/**
* The previous context.
* @type {TryContext}
*/
this.upper = upperContext;
/**
* Indicates if the `try` statement has a `finally` block.
* @type {boolean}
*/
this.hasFinalizer = hasFinalizer;
/**
* Tracks the traversal position inside of the `try` statement. This is
* used to help determine the context necessary to create paths because
* a `try` statement may or may not have `catch` or `finally` blocks,
* and code paths behave differently in those blocks.
* @type {"try"|"catch"|"finally"}
*/
this.position = "try";
/**
* If the `try` statement has a `finally` block, this affects how a
* `return` statement behaves in the `try` block. Without `finally`,
* `return` behaves as usual and doesn't require a fork; with `finally`,
* `return` forks into the `finally` block, so we need a fork context
* to track it.
* @type {ForkContext|null}
*/
this.returnedForkContext = hasFinalizer
? ForkContext.newEmpty(forkContext)
: null;
/**
* When a `throw` occurs inside of a `try` block, the code path forks
* into the `catch` or `finally` blocks, and this fork context tracks
* that path.
* @type {ForkContext}
*/
this.thrownForkContext = ForkContext.newEmpty(forkContext);
/**
* Indicates if the last segment in the `try` block is reachable.
* @type {boolean}
*/
this.lastOfTryIsReachable = false;
/**
* Indicates if the last segment in the `catch` block is reachable.
* @type {boolean}
*/
this.lastOfCatchIsReachable = false;
}
}
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Adds given segments into the `dest` array.
* If the `others` array does not include the given segments, adds to the `all`
* array as well.
*
* This adds only reachable and used segments.
* @param {CodePathSegment[]} dest A destination array (`returnedSegments` or `thrownSegments`).
* @param {CodePathSegment[]} others Another destination array (`returnedSegments` or `thrownSegments`).
* @param {CodePathSegment[]} all The unified destination array (`finalSegments`).
* @param {CodePathSegment[]} segments Segments to add.
* @returns {void}
*/
function addToReturnedOrThrown(dest, others, all, segments) {
for (let i = 0; i < segments.length; ++i) {
const segment = segments[i];
dest.push(segment);
if (!others.includes(segment)) {
all.push(segment);
}
}
}
/**
* Gets a loop context for a `continue` statement based on a given label.
* @param {CodePathState} state The state to search within.
* @param {string|null} label The label of a `continue` statement.
* @returns {LoopContext} A loop-context for a `continue` statement.
*/
function getContinueContext(state, label) {
if (!label) {
return state.loopContext;
}
let context = state.loopContext;
while (context) {
if (context.label === label) {
return context;
}
context = context.upper;
}
/* c8 ignore next */
return null;
}
/**
* Gets a context for a `break` statement.
* @param {CodePathState} state The state to search within.
* @param {string|null} label The label of a `break` statement.
* @returns {BreakContext} A context for a `break` statement.
*/
function getBreakContext(state, label) {
let context = state.breakContext;
while (context) {
if (label ? context.label === label : context.breakable) {
return context;
}
context = context.upper;
}
/* c8 ignore next */
return null;
}
/**
* Gets a context for a `return` statement. There is just one special case:
* if there is a `try` statement with a `finally` block, because that alters
* how `return` behaves; otherwise, this just passes through the given state.
* @param {CodePathState} state The state to search within
* @returns {TryContext|CodePathState} A context for a `return` statement.
*/
function getReturnContext(state) {
let context = state.tryContext;
while (context) {
if (context.hasFinalizer && context.position !== "finally") {
return context;
}
context = context.upper;
}
return state;
}
/**
* Gets a context for a `throw` statement. There is just one special case:
* if there is a `try` statement with a `finally` block and we are inside of
* a `catch` because that changes how `throw` behaves; otherwise, this just
* passes through the given state.
* @param {CodePathState} state The state to search within.
* @returns {TryContext|CodePathState} A context for a `throw` statement.
*/
function getThrowContext(state) {
let context = state.tryContext;
while (context) {
if (context.position === "try" ||
(context.hasFinalizer && context.position === "catch")
) {
return context;
}
context = context.upper;
}
return state;
}
/**
* Removes a given value from a given array.
* @param {any[]} elements An array to remove the specific element.
* @param {any} value The value to be removed.
* @returns {void}
*/
function removeFromArray(elements, value) {
elements.splice(elements.indexOf(value), 1);
}
/**
* Disconnect given segments.
*
* This is used in a process for switch statements.
* If there is the "default" chunk before other cases, the order is different
* between node's and running's.
* @param {CodePathSegment[]} prevSegments Forward segments to disconnect.
* @param {CodePathSegment[]} nextSegments Backward segments to disconnect.
* @returns {void}
*/
function disconnectSegments(prevSegments, nextSegments) {
for (let i = 0; i < prevSegments.length; ++i) {
const prevSegment = prevSegments[i];
const nextSegment = nextSegments[i];
removeFromArray(prevSegment.nextSegments, nextSegment);
removeFromArray(prevSegment.allNextSegments, nextSegment);
removeFromArray(nextSegment.prevSegments, prevSegment);
removeFromArray(nextSegment.allPrevSegments, prevSegment);
}
}
/**
* Creates looping path between two arrays of segments, ensuring that there are
* paths going between matching segments in the arrays.
* @param {CodePathState} state The state to operate on.
* @param {CodePathSegment[]} unflattenedFromSegments Segments which are source.
* @param {CodePathSegment[]} unflattenedToSegments Segments which are destination.
* @returns {void}
*/
function makeLooped(state, unflattenedFromSegments, unflattenedToSegments) {
const fromSegments = CodePathSegment.flattenUnusedSegments(unflattenedFromSegments);
const toSegments = CodePathSegment.flattenUnusedSegments(unflattenedToSegments);
const end = Math.min(fromSegments.length, toSegments.length);
/*
* This loop effectively updates a doubly-linked list between two collections
* of segments making sure that segments in the same array indices are
* combined to create a path.
*/
for (let i = 0; i < end; ++i) {
// get the segments in matching array indices
const fromSegment = fromSegments[i];
const toSegment = toSegments[i];
/*
* If the destination segment is reachable, then create a path from the
* source segment to the destination segment.
*/
if (toSegment.reachable) {
fromSegment.nextSegments.push(toSegment);
}
/*
* If the source segment is reachable, then create a path from the
* destination segment back to the source segment.
*/
if (fromSegment.reachable) {
toSegment.prevSegments.push(fromSegment);
}
/*
* Also update the arrays that don't care if the segments are reachable
* or not. This should always happen regardless of anything else.
*/
fromSegment.allNextSegments.push(toSegment);
toSegment.allPrevSegments.push(fromSegment);
/*
* If the destination segment has at least two previous segments in its
* path then that means there was one previous segment before this iteration
* of the loop was executed. So, we need to mark the source segment as
* looped.
*/
if (toSegment.allPrevSegments.length >= 2) {
CodePathSegment.markPrevSegmentAsLooped(toSegment, fromSegment);
}
// let the code path analyzer know that there's been a loop created
state.notifyLooped(fromSegment, toSegment);
}
}
/**
* Finalizes segments of `test` chunk of a ForStatement.
*
* - Adds `false` paths to paths which are leaving from the loop.
* - Sets `true` paths to paths which go to the body.
* @param {LoopContext} context A loop context to modify.
* @param {ChoiceContext} choiceContext A choice context of this loop.
* @param {CodePathSegment[]} head The current head paths.
* @returns {void}
*/
function finalizeTestSegmentsOfFor(context, choiceContext, head) {
/*
* If this choice context doesn't already contain paths from a
* child context, then add the current head to each potential path.
*/
if (!choiceContext.processed) {
choiceContext.trueForkContext.add(head);
choiceContext.falseForkContext.add(head);
choiceContext.nullishForkContext.add(head);
}
/*
* If the test condition isn't a hardcoded truthy value, then `break`
* must follow the same path as if the test condition is false. To represent
* that, we append the path for when the loop test is false (represented by
* `falseForkContext`) to the `brokenForkContext`.
*/
if (context.test !== true) {
context.brokenForkContext.addAll(choiceContext.falseForkContext);
}
context.endOfTestSegments = choiceContext.trueForkContext.makeNext(0, -1);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* A class which manages state to analyze code paths.
*/
class CodePathState {
/**
* Creates a new instance.
* @param {IdGenerator} idGenerator An id generator to generate id for code
* path segments.
* @param {Function} onLooped A callback function to notify looping.
*/
constructor(idGenerator, onLooped) {
/**
* The ID generator to use when creating new segments.
* @type {IdGenerator}
*/
this.idGenerator = idGenerator;
/**
* A callback function to call when there is a loop.
* @type {Function}
*/
this.notifyLooped = onLooped;
/**
* The root fork context for this state.
* @type {ForkContext}
*/
this.forkContext = ForkContext.newRoot(idGenerator);
/**
* Context for logical expressions, conditional expressions, `if` statements,
* and loops.
* @type {ChoiceContext}
*/
this.choiceContext = null;
/**
* Context for `switch` statements.
* @type {SwitchContext}
*/
this.switchContext = null;
/**
* Context for `try` statements.
* @type {TryContext}
*/
this.tryContext = null;
/**
* Context for loop statements.
* @type {LoopContext}
*/
this.loopContext = null;
/**
* Context for `break` statements.
* @type {BreakContext}
*/
this.breakContext = null;
/**
* Context for `ChainExpression` nodes.
* @type {ChainContext}
*/
this.chainContext = null;
/**
* An array that tracks the current segments in the state. The array
* starts empty and segments are added with each `onCodePathSegmentStart`
* event and removed with each `onCodePathSegmentEnd` event. Effectively,
* this is tracking the code path segment traversal as the state is
* modified.
* @type {Array<CodePathSegment>}
*/
this.currentSegments = [];
/**
* Tracks the starting segment for this path. This value never changes.
* @type {CodePathSegment}
*/
this.initialSegment = this.forkContext.head[0];
/**
* The final segments of the code path which are either `return` or `throw`.
* This is a union of the segments in `returnedForkContext` and `thrownForkContext`.
* @type {Array<CodePathSegment>}
*/
this.finalSegments = [];
/**
* The final segments of the code path which are `return`. These
* segments are also contained in `finalSegments`.
* @type {Array<CodePathSegment>}
*/
this.returnedForkContext = [];
/**
* The final segments of the code path which are `throw`. These
* segments are also contained in `finalSegments`.
* @type {Array<CodePathSegment>}
*/
this.thrownForkContext = [];
/*
* We add an `add` method so that these look more like fork contexts and
* can be used interchangeably when a fork context is needed to add more
* segments to a path.
*
* Ultimately, we want anything added to `returned` or `thrown` to also
* be added to `final`. We only add reachable and used segments to these
* arrays.
*/
const final = this.finalSegments;
const returned = this.returnedForkContext;
const thrown = this.thrownForkContext;
returned.add = addToReturnedOrThrown.bind(null, returned, thrown, final);
thrown.add = addToReturnedOrThrown.bind(null, thrown, returned, final);
}
/**
* A passthrough property exposing the current pointer as part of the API.
* @type {CodePathSegment[]}
*/
get headSegments() {
return this.forkContext.head;
}