forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBuildHIR.ts
4283 lines (4151 loc) · 136 KB
/
BuildHIR.ts
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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {NodePath, Scope} from '@babel/traverse';
import * as t from '@babel/types';
import invariant from 'invariant';
import {
CompilerError,
CompilerSuggestionOperation,
ErrorSeverity,
} from '../CompilerError';
import {Err, Ok, Result} from '../Utils/Result';
import {assertExhaustive, hasNode} from '../Utils/utils';
import {Environment} from './Environment';
import {
ArrayExpression,
ArrayPattern,
BlockId,
BranchTerminal,
BuiltinTag,
Case,
Effect,
GeneratedSource,
GotoVariant,
HIRFunction,
IfTerminal,
InstructionKind,
InstructionValue,
JsxAttribute,
LoweredFunction,
ObjectPattern,
ObjectProperty,
ObjectPropertyKey,
Place,
PropertyLiteral,
ReturnTerminal,
SourceLocation,
SpreadPattern,
ThrowTerminal,
Type,
makeInstructionId,
makePropertyLiteral,
makeType,
promoteTemporary,
} from './HIR';
import HIRBuilder, {Bindings} from './HIRBuilder';
import {BuiltInArrayId} from './ObjectShape';
/*
* *******************************************************************************************
* *******************************************************************************************
* ************************************* Lowering to HIR *************************************
* *******************************************************************************************
* *******************************************************************************************
*/
/*
* Converts a function into a high-level intermediate form (HIR) which represents
* the code as a control-flow graph. All normal control-flow is modeled as accurately
* as possible to allow precise, expression-level memoization. The main exceptions are
* try/catch statements and exceptions: we currently bail out (skip compilation) for
* try/catch and do not attempt to model control flow of exceptions, which can occur
* ~anywhere in JavaScript. The compiler assumes that exceptions will be handled by
* the runtime, ie by invalidating memoization.
*/
export function lower(
func: NodePath<t.Function>,
env: Environment,
bindings: Bindings | null = null,
capturedRefs: Array<t.Identifier> = [],
// the outermost function being compiled, in case lower() is called recursively (for lambdas)
parent: NodePath<t.Function> | null = null,
): Result<HIRFunction, CompilerError> {
const builder = new HIRBuilder(env, parent ?? func, bindings, capturedRefs);
const context: HIRFunction['context'] = [];
for (const ref of capturedRefs ?? []) {
context.push({
kind: 'Identifier',
identifier: builder.resolveBinding(ref),
effect: Effect.Unknown,
reactive: false,
loc: ref.loc ?? GeneratedSource,
});
}
let id: string | null = null;
if (func.isFunctionDeclaration() || func.isFunctionExpression()) {
const idNode = (
func as NodePath<t.FunctionDeclaration | t.FunctionExpression>
).get('id');
if (hasNode(idNode)) {
id = idNode.node.name;
}
}
const params: Array<Place | SpreadPattern> = [];
func.get('params').forEach(param => {
if (param.isIdentifier()) {
const binding = builder.resolveIdentifier(param);
if (binding.kind !== 'Identifier') {
builder.errors.push({
reason: `(BuildHIR::lower) Could not find binding for param \`${param.node.name}\``,
severity: ErrorSeverity.Invariant,
loc: param.node.loc ?? null,
suggestions: null,
});
return;
}
const place: Place = {
kind: 'Identifier',
identifier: binding.identifier,
effect: Effect.Unknown,
reactive: false,
loc: param.node.loc ?? GeneratedSource,
};
params.push(place);
} else if (
param.isObjectPattern() ||
param.isArrayPattern() ||
param.isAssignmentPattern()
) {
const place: Place = {
kind: 'Identifier',
identifier: builder.makeTemporary(param.node.loc ?? GeneratedSource),
effect: Effect.Unknown,
reactive: false,
loc: param.node.loc ?? GeneratedSource,
};
promoteTemporary(place.identifier);
params.push(place);
lowerAssignment(
builder,
param.node.loc ?? GeneratedSource,
InstructionKind.Let,
param,
place,
'Assignment',
);
} else if (param.isRestElement()) {
const place: Place = {
kind: 'Identifier',
identifier: builder.makeTemporary(param.node.loc ?? GeneratedSource),
effect: Effect.Unknown,
reactive: false,
loc: param.node.loc ?? GeneratedSource,
};
params.push({
kind: 'Spread',
place,
});
lowerAssignment(
builder,
param.node.loc ?? GeneratedSource,
InstructionKind.Let,
param.get('argument'),
place,
'Assignment',
);
} else {
builder.errors.push({
reason: `(BuildHIR::lower) Handle ${param.node.type} params`,
severity: ErrorSeverity.Todo,
loc: param.node.loc ?? null,
suggestions: null,
});
}
});
let directives: Array<string> = [];
const body = func.get('body');
if (body.isExpression()) {
const fallthrough = builder.reserve('block');
const terminal: ReturnTerminal = {
kind: 'return',
loc: GeneratedSource,
value: lowerExpressionToTemporary(builder, body),
id: makeInstructionId(0),
};
builder.terminateWithContinuation(terminal, fallthrough);
} else if (body.isBlockStatement()) {
lowerStatement(builder, body);
directives = body.get('directives').map(d => d.node.value.value);
} else {
builder.errors.push({
severity: ErrorSeverity.InvalidJS,
reason: `Unexpected function body kind`,
description: `Expected function body to be an expression or a block statement, got \`${body.type}\``,
loc: body.node.loc ?? null,
suggestions: null,
});
}
if (builder.errors.hasErrors()) {
return Err(builder.errors);
}
builder.terminate(
{
kind: 'return',
loc: GeneratedSource,
value: lowerValueToTemporary(builder, {
kind: 'Primitive',
value: undefined,
loc: GeneratedSource,
}),
id: makeInstructionId(0),
},
null,
);
return Ok({
id,
params,
fnType: parent == null ? env.fnType : 'Other',
returnTypeAnnotation: null, // TODO: extract the actual return type node if present
returnType: makeType(),
body: builder.build(),
context,
generator: func.node.generator === true,
async: func.node.async === true,
loc: func.node.loc ?? GeneratedSource,
env,
effects: null,
directives,
});
}
// Helper to lower a statement
function lowerStatement(
builder: HIRBuilder,
stmtPath: NodePath<t.Statement>,
label: string | null = null,
): void {
const stmtNode = stmtPath.node;
switch (stmtNode.type) {
case 'ThrowStatement': {
const stmt = stmtPath as NodePath<t.ThrowStatement>;
const value = lowerExpressionToTemporary(builder, stmt.get('argument'));
const handler = builder.resolveThrowHandler();
if (handler != null) {
/*
* NOTE: we could support this, but a `throw` inside try/catch is using exceptions
* for control-flow and is generally considered an anti-pattern. we can likely
* just not support this pattern, unless it really becomes necessary for some reason.
*/
builder.errors.push({
reason:
'(BuildHIR::lowerStatement) Support ThrowStatement inside of try/catch',
severity: ErrorSeverity.Todo,
loc: stmt.node.loc ?? null,
suggestions: null,
});
}
const terminal: ThrowTerminal = {
kind: 'throw',
value,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
};
builder.terminate(terminal, 'block');
return;
}
case 'ReturnStatement': {
const stmt = stmtPath as NodePath<t.ReturnStatement>;
const argument = stmt.get('argument');
let value;
if (argument.node === null) {
value = lowerValueToTemporary(builder, {
kind: 'Primitive',
value: undefined,
loc: GeneratedSource,
});
} else {
value = lowerExpressionToTemporary(
builder,
argument as NodePath<t.Expression>,
);
}
const terminal: ReturnTerminal = {
kind: 'return',
loc: stmt.node.loc ?? GeneratedSource,
value,
id: makeInstructionId(0),
};
builder.terminate(terminal, 'block');
return;
}
case 'IfStatement': {
const stmt = stmtPath as NodePath<t.IfStatement>;
// Block for code following the if
const continuationBlock = builder.reserve('block');
// Block for the consequent (if the test is truthy)
const consequentBlock = builder.enter('block', _blockId => {
const consequent = stmt.get('consequent');
lowerStatement(builder, consequent);
return {
kind: 'goto',
block: continuationBlock.id,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: consequent.node.loc ?? GeneratedSource,
};
});
// Block for the alternate (if the test is not truthy)
let alternateBlock: BlockId;
const alternate = stmt.get('alternate');
if (hasNode(alternate)) {
alternateBlock = builder.enter('block', _blockId => {
lowerStatement(builder, alternate);
return {
kind: 'goto',
block: continuationBlock.id,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: alternate.node?.loc ?? GeneratedSource,
};
});
} else {
// If there is no else clause, use the continuation directly
alternateBlock = continuationBlock.id;
}
const test = lowerExpressionToTemporary(builder, stmt.get('test'));
const terminal: IfTerminal = {
kind: 'if',
test,
consequent: consequentBlock,
alternate: alternateBlock,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
};
builder.terminateWithContinuation(terminal, continuationBlock);
return;
}
case 'BlockStatement': {
const stmt = stmtPath as NodePath<t.BlockStatement>;
const statements = stmt.get('body');
/**
* Hoistable identifier bindings defined for this precise block
* scope (excluding bindings from parent or child block scopes).
*/
const hoistableIdentifiers: Set<t.Identifier> = new Set();
for (const [, binding] of Object.entries(stmt.scope.bindings)) {
// refs to params are always valid / never need to be hoisted
if (binding.kind !== 'param') {
hoistableIdentifiers.add(binding.identifier);
}
}
for (const s of statements) {
const willHoist = new Set<NodePath<t.Identifier>>();
/*
* If we see a hoistable identifier before its declaration, it should be hoisted just
* before the statement that references it.
*/
let fnDepth = s.isFunctionDeclaration() ? 1 : 0;
const withFunctionContext = {
enter: (): void => {
fnDepth++;
},
exit: (): void => {
fnDepth--;
},
};
s.traverse({
FunctionExpression: withFunctionContext,
FunctionDeclaration: withFunctionContext,
ArrowFunctionExpression: withFunctionContext,
ObjectMethod: withFunctionContext,
Identifier(id: NodePath<t.Identifier>) {
const id2 = id;
if (
!id2.isReferencedIdentifier() &&
// isReferencedIdentifier is broken and returns false for reassignments
id.parent.type !== 'AssignmentExpression'
) {
return;
}
const binding = id.scope.getBinding(id.node.name);
/**
* We can only hoist an identifier decl if
* 1. the reference occurs within an inner function
* or
* 2. the declaration itself is hoistable
*/
if (
binding != null &&
hoistableIdentifiers.has(binding.identifier) &&
(fnDepth > 0 || binding.kind === 'hoisted')
) {
willHoist.add(id);
}
},
});
/*
* After visiting the declaration, hoisting is no longer required
*/
s.traverse({
Identifier(path: NodePath<t.Identifier>) {
if (hoistableIdentifiers.has(path.node)) {
hoistableIdentifiers.delete(path.node);
}
},
});
// Hoist declarations that need it to the earliest point where they are needed
for (const id of willHoist) {
const binding = stmt.scope.getBinding(id.node.name);
CompilerError.invariant(binding != null, {
reason: 'Expected to find binding for hoisted identifier',
description: `Could not find a binding for ${id.node.name}`,
suggestions: null,
loc: id.node.loc ?? GeneratedSource,
});
if (builder.environment.isHoistedIdentifier(binding.identifier)) {
// Already hoisted
continue;
}
let kind:
| InstructionKind.Let
| InstructionKind.HoistedConst
| InstructionKind.HoistedLet
| InstructionKind.HoistedFunction;
if (binding.kind === 'const' || binding.kind === 'var') {
kind = InstructionKind.HoistedConst;
} else if (binding.kind === 'let') {
kind = InstructionKind.HoistedLet;
} else if (binding.path.isFunctionDeclaration()) {
kind = InstructionKind.HoistedFunction;
} else if (!binding.path.isVariableDeclarator()) {
builder.errors.push({
severity: ErrorSeverity.Todo,
reason: 'Unsupported declaration type for hoisting',
description: `variable "${binding.identifier.name}" declared with ${binding.path.type}`,
suggestions: null,
loc: id.parentPath.node.loc ?? GeneratedSource,
});
continue;
} else {
builder.errors.push({
severity: ErrorSeverity.Todo,
reason: 'Handle non-const declarations for hoisting',
description: `variable "${binding.identifier.name}" declared with ${binding.kind}`,
suggestions: null,
loc: id.parentPath.node.loc ?? GeneratedSource,
});
continue;
}
const identifier = builder.resolveIdentifier(id);
CompilerError.invariant(identifier.kind === 'Identifier', {
reason:
'Expected hoisted binding to be a local identifier, not a global',
loc: id.node.loc ?? GeneratedSource,
});
const place: Place = {
effect: Effect.Unknown,
identifier: identifier.identifier,
kind: 'Identifier',
reactive: false,
loc: id.node.loc ?? GeneratedSource,
};
lowerValueToTemporary(builder, {
kind: 'DeclareContext',
lvalue: {
kind,
place,
},
loc: id.node.loc ?? GeneratedSource,
});
builder.environment.addHoistedIdentifier(binding.identifier);
}
lowerStatement(builder, s);
}
return;
}
case 'BreakStatement': {
const stmt = stmtPath as NodePath<t.BreakStatement>;
const block = builder.lookupBreak(stmt.node.label?.name ?? null);
builder.terminate(
{
kind: 'goto',
block,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
},
'block',
);
return;
}
case 'ContinueStatement': {
const stmt = stmtPath as NodePath<t.ContinueStatement>;
const block = builder.lookupContinue(stmt.node.label?.name ?? null);
builder.terminate(
{
kind: 'goto',
block,
variant: GotoVariant.Continue,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
},
'block',
);
return;
}
case 'ForStatement': {
const stmt = stmtPath as NodePath<t.ForStatement>;
const testBlock = builder.reserve('loop');
// Block for code following the loop
const continuationBlock = builder.reserve('block');
const initBlock = builder.enter('loop', _blockId => {
const init = stmt.get('init');
if (!init.isVariableDeclaration()) {
builder.errors.push({
reason:
'(BuildHIR::lowerStatement) Handle non-variable initialization in ForStatement',
severity: ErrorSeverity.Todo,
loc: stmt.node.loc ?? null,
suggestions: null,
});
return {
kind: 'unsupported',
id: makeInstructionId(0),
loc: init.node?.loc ?? GeneratedSource,
};
}
lowerStatement(builder, init);
return {
kind: 'goto',
block: testBlock.id,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: init.node.loc ?? GeneratedSource,
};
});
let updateBlock: BlockId | null = null;
const update = stmt.get('update');
if (hasNode(update)) {
updateBlock = builder.enter('loop', _blockId => {
lowerExpressionToTemporary(builder, update);
return {
kind: 'goto',
block: testBlock.id,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: update.node?.loc ?? GeneratedSource,
};
});
}
const bodyBlock = builder.enter('block', _blockId => {
return builder.loop(
label,
updateBlock ?? testBlock.id,
continuationBlock.id,
() => {
const body = stmt.get('body');
lowerStatement(builder, body);
return {
kind: 'goto',
block: updateBlock ?? testBlock.id,
variant: GotoVariant.Continue,
id: makeInstructionId(0),
loc: body.node.loc ?? GeneratedSource,
};
},
);
});
builder.terminateWithContinuation(
{
kind: 'for',
loc: stmtNode.loc ?? GeneratedSource,
init: initBlock,
test: testBlock.id,
update: updateBlock,
loop: bodyBlock,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
},
testBlock,
);
const test = stmt.get('test');
if (test.node == null) {
builder.errors.push({
reason: `(BuildHIR::lowerStatement) Handle empty test in ForStatement`,
severity: ErrorSeverity.Todo,
loc: stmt.node.loc ?? null,
suggestions: null,
});
} else {
builder.terminateWithContinuation(
{
kind: 'branch',
test: lowerExpressionToTemporary(
builder,
test as NodePath<t.Expression>,
),
consequent: bodyBlock,
alternate: continuationBlock.id,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
},
continuationBlock,
);
}
return;
}
case 'WhileStatement': {
const stmt = stmtPath as NodePath<t.WhileStatement>;
// Block used to evaluate whether to (re)enter or exit the loop
const conditionalBlock = builder.reserve('loop');
// Block for code following the loop
const continuationBlock = builder.reserve('block');
// Loop body
const loopBlock = builder.enter('block', _blockId => {
return builder.loop(
label,
conditionalBlock.id,
continuationBlock.id,
() => {
const body = stmt.get('body');
lowerStatement(builder, body);
return {
kind: 'goto',
block: conditionalBlock.id,
variant: GotoVariant.Continue,
id: makeInstructionId(0),
loc: body.node.loc ?? GeneratedSource,
};
},
);
});
/*
* The code leading up to the loop must jump to the conditional block,
* to evaluate whether to enter the loop or bypass to the continuation.
*/
const loc = stmt.node.loc ?? GeneratedSource;
builder.terminateWithContinuation(
{
kind: 'while',
loc,
test: conditionalBlock.id,
loop: loopBlock,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
},
conditionalBlock,
);
const test = lowerExpressionToTemporary(builder, stmt.get('test'));
const terminal: BranchTerminal = {
kind: 'branch',
test,
consequent: loopBlock,
alternate: continuationBlock.id,
fallthrough: conditionalBlock.id,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
};
// Complete the conditional and continue with code after the loop
builder.terminateWithContinuation(terminal, continuationBlock);
return;
}
case 'LabeledStatement': {
const stmt = stmtPath as NodePath<t.LabeledStatement>;
const label = stmt.node.label.name;
const body = stmt.get('body');
switch (body.node.type) {
case 'ForInStatement':
case 'ForOfStatement':
case 'ForStatement':
case 'WhileStatement':
case 'DoWhileStatement': {
/*
* labeled loops are special because of continue, so push the label
* down
*/
lowerStatement(builder, stmt.get('body'), label);
break;
}
default: {
/*
* All other statements create a continuation block to allow `break`,
* explicitly *don't* pass the label down
*/
const continuationBlock = builder.reserve('block');
const block = builder.enter('block', () => {
const body = stmt.get('body');
builder.label(label, continuationBlock.id, () => {
lowerStatement(builder, body);
});
return {
kind: 'goto',
block: continuationBlock.id,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: body.node.loc ?? GeneratedSource,
};
});
builder.terminateWithContinuation(
{
kind: 'label',
block,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
},
continuationBlock,
);
}
}
return;
}
case 'SwitchStatement': {
const stmt = stmtPath as NodePath<t.SwitchStatement>;
// Block following the switch
const continuationBlock = builder.reserve('block');
/*
* The goto target for any cases that fallthrough, which initially starts
* as the continuation block and is then updated as we iterate through cases
* in reverse order.
*/
let fallthrough = continuationBlock.id;
/*
* Iterate through cases in reverse order, so that previous blocks can fallthrough
* to successors
*/
const cases: Array<Case> = [];
let hasDefault = false;
for (let ii = stmt.get('cases').length - 1; ii >= 0; ii--) {
const case_: NodePath<t.SwitchCase> = stmt.get('cases')[ii];
const testExpr = case_.get('test');
if (testExpr.node == null) {
if (hasDefault) {
builder.errors.push({
reason: `Expected at most one \`default\` branch in a switch statement, this code should have failed to parse`,
severity: ErrorSeverity.InvalidJS,
loc: case_.node.loc ?? null,
suggestions: null,
});
break;
}
hasDefault = true;
}
const block = builder.enter('block', _blockId => {
return builder.switch(label, continuationBlock.id, () => {
case_
.get('consequent')
.forEach(consequent => lowerStatement(builder, consequent));
/*
* always generate a fallthrough to the next block, this may be dead code
* if there was an explicit break, but if so it will be pruned later.
*/
return {
kind: 'goto',
block: fallthrough,
variant: GotoVariant.Break,
id: makeInstructionId(0),
loc: case_.node.loc ?? GeneratedSource,
};
});
});
let test: Place | null = null;
if (hasNode(testExpr)) {
test = lowerReorderableExpression(builder, testExpr);
}
cases.push({
test,
block,
});
fallthrough = block;
}
/*
* it doesn't matter for our analysis purposes, but reverse the order of the cases
* back to the original to make it match the original code/intent.
*/
cases.reverse();
/*
* If there wasn't an explicit default case, generate one to model the fact that execution
* could bypass any of the other cases and jump directly to the continuation.
*/
if (!hasDefault) {
cases.push({test: null, block: continuationBlock.id});
}
const test = lowerExpressionToTemporary(
builder,
stmt.get('discriminant'),
);
builder.terminateWithContinuation(
{
kind: 'switch',
test,
cases,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
loc: stmt.node.loc ?? GeneratedSource,
},
continuationBlock,
);
return;
}
case 'VariableDeclaration': {
const stmt = stmtPath as NodePath<t.VariableDeclaration>;
const nodeKind: t.VariableDeclaration['kind'] = stmt.node.kind;
if (nodeKind === 'var') {
builder.errors.push({
reason: `(BuildHIR::lowerStatement) Handle ${nodeKind} kinds in VariableDeclaration`,
severity: ErrorSeverity.Todo,
loc: stmt.node.loc ?? null,
suggestions: null,
});
return;
}
const kind =
nodeKind === 'let' ? InstructionKind.Let : InstructionKind.Const;
for (const declaration of stmt.get('declarations')) {
const id = declaration.get('id');
const init = declaration.get('init');
if (hasNode(init)) {
const value = lowerExpressionToTemporary(builder, init);
lowerAssignment(
builder,
stmt.node.loc ?? GeneratedSource,
kind,
id,
value,
id.isObjectPattern() || id.isArrayPattern()
? 'Destructure'
: 'Assignment',
);
} else if (id.isIdentifier()) {
const binding = builder.resolveIdentifier(id);
if (binding.kind !== 'Identifier') {
builder.errors.push({
reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`,
severity: ErrorSeverity.Invariant,
loc: id.node.loc ?? null,
suggestions: null,
});
} else {
const place: Place = {
effect: Effect.Unknown,
identifier: binding.identifier,
kind: 'Identifier',
reactive: false,
loc: id.node.loc ?? GeneratedSource,
};
if (builder.isContextIdentifier(id)) {
if (kind === InstructionKind.Const) {
const declRangeStart = declaration.parentPath.node.start!;
builder.errors.push({
reason: `Expect \`const\` declaration not to be reassigned`,
severity: ErrorSeverity.InvalidJS,
loc: id.node.loc ?? null,
suggestions: [
{
description: 'Change to a `let` declaration',
op: CompilerSuggestionOperation.Replace,
range: [declRangeStart, declRangeStart + 5], // "const".length
text: 'let',
},
],
});
}
lowerValueToTemporary(builder, {
kind: 'DeclareContext',
lvalue: {
kind: InstructionKind.Let,
place,
},
loc: id.node.loc ?? GeneratedSource,
});
} else {
const typeAnnotation = id.get('typeAnnotation');
let type: t.FlowType | t.TSType | null;
if (typeAnnotation.isTSTypeAnnotation()) {
const typePath = typeAnnotation.get('typeAnnotation');
type = typePath.node;
} else if (typeAnnotation.isTypeAnnotation()) {
const typePath = typeAnnotation.get('typeAnnotation');
type = typePath.node;
} else {
type = null;
}
lowerValueToTemporary(builder, {
kind: 'DeclareLocal',
lvalue: {
kind,
place,
},
type,
loc: id.node.loc ?? GeneratedSource,
});
}
}
} else {
builder.errors.push({
reason: `Expected variable declaration to be an identifier if no initializer was provided`,
description: `Got a \`${id.type}\``,
severity: ErrorSeverity.InvalidJS,
loc: stmt.node.loc ?? null,
suggestions: null,
});
}
}
return;
}
case 'ExpressionStatement': {
const stmt = stmtPath as NodePath<t.ExpressionStatement>;
const expression = stmt.get('expression');
lowerExpressionToTemporary(builder, expression);
return;
}
case 'DoWhileStatement': {
const stmt = stmtPath as NodePath<t.DoWhileStatement>;
// Block used to evaluate whether to (re)enter or exit the loop
const conditionalBlock = builder.reserve('loop');
// Block for code following the loop
const continuationBlock = builder.reserve('block');
// Loop body, executed at least once uncondtionally prior to exit
const loopBlock = builder.enter('block', _loopBlockId => {
return builder.loop(
label,
conditionalBlock.id,
continuationBlock.id,
() => {
const body = stmt.get('body');
lowerStatement(builder, body);
return {
kind: 'goto',
block: conditionalBlock.id,
variant: GotoVariant.Continue,
id: makeInstructionId(0),
loc: body.node.loc ?? GeneratedSource,
};
},
);
});
/*
* Jump to the conditional block to evaluate whether to (re)enter the loop or exit to the
* continuation block.
*/
const loc = stmt.node.loc ?? GeneratedSource;
builder.terminateWithContinuation(
{
kind: 'do-while',
loc,
test: conditionalBlock.id,
loop: loopBlock,
fallthrough: continuationBlock.id,
id: makeInstructionId(0),
},
conditionalBlock,
);
/*
* The conditional block is empty and exists solely as conditional for
* (re)entering or exiting the loop
*/
const test = lowerExpressionToTemporary(builder, stmt.get('test'));
const terminal: BranchTerminal = {
kind: 'branch',
test,
consequent: loopBlock,
alternate: continuationBlock.id,
fallthrough: conditionalBlock.id,
id: makeInstructionId(0),
loc,
};
// Complete the conditional and continue with code after the loop
builder.terminateWithContinuation(terminal, continuationBlock);
return;
}
case 'FunctionDeclaration': {
const stmt = stmtPath as NodePath<t.FunctionDeclaration>;
stmt.skip();
CompilerError.invariant(stmt.get('id').type === 'Identifier', {
reason: 'function declarations must have a name',
description: null,
loc: stmt.node.loc ?? null,
suggestions: null,
});
const id = stmt.get('id') as NodePath<t.Identifier>;
const fn = lowerValueToTemporary(
builder,
lowerFunctionToValue(builder, stmt),