hermes-parser 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,886 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ * @flow strict
8
+ * @format
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ /**
14
+ * Transform match expressions and statements.
15
+ */
16
+
17
+ import type {ParserOptions} from '../ParserOptions';
18
+ import type {
19
+ BinaryExpression,
20
+ BreakStatement,
21
+ ESNode,
22
+ Expression,
23
+ Identifier,
24
+ Literal,
25
+ MatchExpression,
26
+ MatchMemberPattern,
27
+ MatchPattern,
28
+ MatchStatement,
29
+ MemberExpression,
30
+ ObjectPattern,
31
+ Program,
32
+ Statement,
33
+ Super,
34
+ UnaryExpression,
35
+ VariableDeclaration,
36
+ } from 'hermes-estree';
37
+
38
+ import {SimpleTransform} from '../transform/SimpleTransform';
39
+ import {
40
+ deepCloneNode,
41
+ shallowCloneNode,
42
+ } from '../transform/astNodeMutationHelpers';
43
+ import {createSyntaxError} from '../utils/createSyntaxError';
44
+ import {
45
+ EMPTY_PARENT,
46
+ callExpression,
47
+ conjunction,
48
+ disjunction,
49
+ etc,
50
+ ident,
51
+ iife,
52
+ nullLiteral,
53
+ numberLiteral,
54
+ stringLiteral,
55
+ throwStatement,
56
+ variableDeclaration,
57
+ } from '../utils/Builders';
58
+ import {createGenID} from '../utils/GenID';
59
+
60
+ /**
61
+ * Generated identifiers.
62
+ * `GenID` is initialized in the transform.
63
+ */
64
+ let GenID: ?ReturnType<typeof createGenID> = null;
65
+ function genIdent(): Identifier {
66
+ if (GenID == null) {
67
+ throw Error('GenID must be initialized at the start of the transform.');
68
+ }
69
+ return ident(GenID.genID());
70
+ }
71
+
72
+ /**
73
+ * A series of properties.
74
+ * When combined with the match argument (the root expression), provides the
75
+ * location of to be tested against, or location to be extracted to a binding.
76
+ */
77
+ type Key = Array<Identifier | Literal>;
78
+
79
+ /**
80
+ * The conditional aspect of a match pattern for a single location.
81
+ */
82
+ type Condition =
83
+ | {type: 'eq', key: Key, arg: Expression}
84
+ | {type: 'is-nan', key: Key}
85
+ | {type: 'array', key: Key, length: number, lengthOp: 'eq' | 'gte'}
86
+ | {type: 'object', key: Key}
87
+ | {type: 'prop-exists', key: Key, propName: string}
88
+ | {type: 'or', orConditions: Array<Array<Condition>>};
89
+
90
+ /**
91
+ * A binding introduced by a match pattern.
92
+ */
93
+ type Binding =
94
+ | {type: 'id', key: Key, kind: BindingKind, id: Identifier}
95
+ | {
96
+ type: 'array-rest',
97
+ key: Key,
98
+ kind: BindingKind,
99
+ id: Identifier,
100
+ exclude: number,
101
+ }
102
+ | {
103
+ type: 'object-rest',
104
+ key: Key,
105
+ kind: BindingKind,
106
+ id: Identifier,
107
+ exclude: Array<Identifier | Literal>,
108
+ };
109
+ type BindingKind = VariableDeclaration['kind'];
110
+
111
+ function objKeyToString(node: Identifier | Literal): string {
112
+ switch (node.type) {
113
+ case 'Identifier':
114
+ return node.name;
115
+ case 'Literal': {
116
+ const {value} = node;
117
+ if (typeof value === 'number') {
118
+ return String(value);
119
+ } else if (typeof value === 'string') {
120
+ return value;
121
+ } else {
122
+ return node.raw;
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ function convertMemberPattern(pattern: MatchMemberPattern): MemberExpression {
129
+ const {base, property, loc, range} = pattern;
130
+ const object =
131
+ base.type === 'MatchIdentifierPattern'
132
+ ? base.id
133
+ : convertMemberPattern(base);
134
+ if (property.type === 'Identifier') {
135
+ return {
136
+ type: 'MemberExpression',
137
+ object,
138
+ property,
139
+ computed: false,
140
+ optional: false,
141
+ ...etc({loc, range}),
142
+ };
143
+ } else {
144
+ return {
145
+ type: 'MemberExpression',
146
+ object,
147
+ property,
148
+ computed: true,
149
+ optional: false,
150
+ ...etc({loc, range}),
151
+ };
152
+ }
153
+ }
154
+
155
+ function checkDuplicateBindingName(
156
+ seenBindingNames: Set<string>,
157
+ node: MatchPattern,
158
+ name: string,
159
+ ): void {
160
+ if (seenBindingNames.has(name)) {
161
+ throw createSyntaxError(
162
+ node,
163
+ `Duplicate variable name '${name}' in match case pattern.`,
164
+ );
165
+ }
166
+ seenBindingNames.add(name);
167
+ }
168
+
169
+ function checkBindingKind(node: MatchPattern, kind: BindingKind): void {
170
+ if (kind === 'var') {
171
+ throw createSyntaxError(
172
+ node,
173
+ `'var' bindings are not allowed. Use 'const' or 'let'.`,
174
+ );
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Analyzes a match pattern, and produced both the conditions and bindings
180
+ * produced by that pattern.
181
+ */
182
+ function analyzePattern(
183
+ pattern: MatchPattern,
184
+ key: Key,
185
+ seenBindingNames: Set<string>,
186
+ ): {
187
+ conditions: Array<Condition>,
188
+ bindings: Array<Binding>,
189
+ } {
190
+ switch (pattern.type) {
191
+ case 'MatchWildcardPattern': {
192
+ return {conditions: [], bindings: []};
193
+ }
194
+ case 'MatchLiteralPattern': {
195
+ const {literal} = pattern;
196
+ const condition: Condition = {type: 'eq', key, arg: literal};
197
+ return {conditions: [condition], bindings: []};
198
+ }
199
+ case 'MatchUnaryPattern': {
200
+ const {operator, argument, loc, range} = pattern;
201
+ if (argument.value === 0) {
202
+ // We haven't decided whether we will compare these using `===` or `Object.is`
203
+ throw createSyntaxError(
204
+ pattern,
205
+ `'+0' and '-0' are not yet supported in match unary patterns.`,
206
+ );
207
+ }
208
+ const arg: UnaryExpression = {
209
+ type: 'UnaryExpression',
210
+ operator,
211
+ argument,
212
+ prefix: true,
213
+ ...etc({loc, range}),
214
+ };
215
+ const condition: Condition = {type: 'eq', key, arg};
216
+ return {conditions: [condition], bindings: []};
217
+ }
218
+ case 'MatchIdentifierPattern': {
219
+ const {id} = pattern;
220
+ const condition: Condition =
221
+ id.name === 'NaN' ? {type: 'is-nan', key} : {type: 'eq', key, arg: id};
222
+ return {conditions: [condition], bindings: []};
223
+ }
224
+ case 'MatchMemberPattern': {
225
+ const arg = convertMemberPattern(pattern);
226
+ const condition: Condition = {type: 'eq', key, arg};
227
+ return {conditions: [condition], bindings: []};
228
+ }
229
+ case 'MatchBindingPattern': {
230
+ const {id, kind} = pattern;
231
+ checkDuplicateBindingName(seenBindingNames, pattern, id.name);
232
+ checkBindingKind(pattern, kind);
233
+ const binding: Binding = {type: 'id', key, kind, id};
234
+ return {conditions: [], bindings: [binding]};
235
+ }
236
+ case 'MatchAsPattern': {
237
+ const {pattern: asPattern, target} = pattern;
238
+ if (asPattern.type === 'MatchBindingPattern') {
239
+ throw createSyntaxError(
240
+ pattern,
241
+ `Match 'as' patterns are not allowed directly on binding patterns.`,
242
+ );
243
+ }
244
+ const {conditions, bindings} = analyzePattern(
245
+ asPattern,
246
+ key,
247
+ seenBindingNames,
248
+ );
249
+ const [id, kind] =
250
+ target.type === 'MatchBindingPattern'
251
+ ? [target.id, target.kind]
252
+ : [target, 'const'];
253
+ checkDuplicateBindingName(seenBindingNames, pattern, id.name);
254
+ checkBindingKind(pattern, kind);
255
+ const binding: Binding = {type: 'id', key, kind, id};
256
+ return {conditions, bindings: bindings.concat(binding)};
257
+ }
258
+ case 'MatchArrayPattern': {
259
+ const {elements, rest} = pattern;
260
+ const lengthOp = rest == null ? 'eq' : 'gte';
261
+ const conditions: Array<Condition> = [
262
+ {type: 'array', key, length: elements.length, lengthOp},
263
+ ];
264
+ const bindings: Array<Binding> = [];
265
+ elements.forEach((element, i) => {
266
+ const elementKey = key.concat(numberLiteral(i));
267
+ const {conditions: childConditions, bindings: childBindings} =
268
+ analyzePattern(element, elementKey, seenBindingNames);
269
+ conditions.push(...childConditions);
270
+ bindings.push(...childBindings);
271
+ });
272
+ if (rest != null && rest.argument != null) {
273
+ const {id, kind} = rest.argument;
274
+ checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
275
+ checkBindingKind(pattern, kind);
276
+ bindings.push({
277
+ type: 'array-rest',
278
+ key,
279
+ exclude: elements.length,
280
+ kind,
281
+ id,
282
+ });
283
+ }
284
+ return {conditions, bindings};
285
+ }
286
+ case 'MatchObjectPattern': {
287
+ const {properties, rest} = pattern;
288
+ const conditions: Array<Condition> = [{type: 'object', key}];
289
+ const bindings: Array<Binding> = [];
290
+ const objKeys: Array<Identifier | Literal> = [];
291
+ const seenNames = new Set<string>();
292
+ properties.forEach(prop => {
293
+ const {key: objKey, pattern: propPattern} = prop;
294
+ objKeys.push(objKey);
295
+ const name = objKeyToString(objKey);
296
+ if (seenNames.has(name)) {
297
+ throw createSyntaxError(
298
+ propPattern,
299
+ `Duplicate property name '${name}' in match object pattern.`,
300
+ );
301
+ }
302
+ seenNames.add(name);
303
+ const propKey: Key = key.concat(objKey);
304
+ switch (propPattern.type) {
305
+ case 'MatchWildcardPattern':
306
+ case 'MatchBindingPattern':
307
+ conditions.push({
308
+ type: 'prop-exists',
309
+ key,
310
+ propName: name,
311
+ });
312
+ break;
313
+ }
314
+ const {conditions: childConditions, bindings: childBindings} =
315
+ analyzePattern(propPattern, propKey, seenBindingNames);
316
+ conditions.push(...childConditions);
317
+ bindings.push(...childBindings);
318
+ });
319
+ if (rest != null && rest.argument != null) {
320
+ const {id, kind} = rest.argument;
321
+ checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
322
+ checkBindingKind(pattern, kind);
323
+ bindings.push({
324
+ type: 'object-rest',
325
+ key,
326
+ exclude: objKeys,
327
+ kind,
328
+ id,
329
+ });
330
+ }
331
+ return {conditions, bindings};
332
+ }
333
+ case 'MatchOrPattern': {
334
+ const {patterns} = pattern;
335
+ let hasWildcard = false;
336
+ const orConditions = patterns.map(subpattern => {
337
+ const {conditions, bindings} = analyzePattern(
338
+ subpattern,
339
+ key,
340
+ seenBindingNames,
341
+ );
342
+ if (bindings.length > 0) {
343
+ // We will implement this in the future.
344
+ throw createSyntaxError(
345
+ pattern,
346
+ `Bindings in match 'or' patterns are not yet supported.`,
347
+ );
348
+ }
349
+ if (conditions.length === 0) {
350
+ hasWildcard = true;
351
+ }
352
+ return conditions;
353
+ });
354
+ if (hasWildcard) {
355
+ return {conditions: [], bindings: []};
356
+ }
357
+ return {
358
+ conditions: [{type: 'or', orConditions}],
359
+ bindings: [],
360
+ };
361
+ }
362
+ }
363
+ }
364
+
365
+ function expressionOfKey(root: Expression, key: Key): Expression {
366
+ return key.reduce(
367
+ (acc, prop) =>
368
+ prop.type === 'Identifier'
369
+ ? {
370
+ type: 'MemberExpression',
371
+ object: acc,
372
+ property: shallowCloneNode(prop),
373
+ computed: false,
374
+ optional: false,
375
+ ...etc(),
376
+ }
377
+ : {
378
+ type: 'MemberExpression',
379
+ object: acc,
380
+ property: shallowCloneNode(prop),
381
+ computed: true,
382
+ optional: false,
383
+ ...etc(),
384
+ },
385
+ deepCloneNode(root),
386
+ );
387
+ }
388
+
389
+ function testsOfCondition(
390
+ root: Expression,
391
+ condition: Condition,
392
+ ): Array<Expression> {
393
+ switch (condition.type) {
394
+ case 'eq': {
395
+ // <x> === <arg>
396
+ const {key, arg} = condition;
397
+ return [
398
+ {
399
+ type: 'BinaryExpression',
400
+ left: expressionOfKey(root, key),
401
+ right: arg,
402
+ operator: '===',
403
+ ...etc(),
404
+ },
405
+ ];
406
+ }
407
+ case 'is-nan': {
408
+ // Number.isNaN(<x>)
409
+ const {key} = condition;
410
+ const callee: MemberExpression = {
411
+ type: 'MemberExpression',
412
+ object: ident('Number'),
413
+ property: ident('isNaN'),
414
+ computed: false,
415
+ optional: false,
416
+ ...etc(),
417
+ };
418
+ return [callExpression(callee, [expressionOfKey(root, key)])];
419
+ }
420
+ case 'array': {
421
+ // Array.isArray(<x>) && <x>.length === <length>
422
+ const {key, length, lengthOp} = condition;
423
+ const operator = lengthOp === 'eq' ? '===' : '>=';
424
+ const isArray = callExpression(
425
+ {
426
+ type: 'MemberExpression',
427
+ object: ident('Array'),
428
+ property: ident('isArray'),
429
+ computed: false,
430
+ optional: false,
431
+ ...etc(),
432
+ },
433
+ [expressionOfKey(root, key)],
434
+ );
435
+ const lengthCheck: BinaryExpression = {
436
+ type: 'BinaryExpression',
437
+ left: {
438
+ type: 'MemberExpression',
439
+ object: expressionOfKey(root, key),
440
+ property: ident('length'),
441
+ computed: false,
442
+ optional: false,
443
+ ...etc(),
444
+ },
445
+ right: numberLiteral(length),
446
+ operator,
447
+ ...etc(),
448
+ };
449
+ return [isArray, lengthCheck];
450
+ }
451
+ case 'object': {
452
+ // typeof <x> === 'object' && <x> !== null
453
+ const {key} = condition;
454
+ const typeofObject: BinaryExpression = {
455
+ type: 'BinaryExpression',
456
+ left: {
457
+ type: 'UnaryExpression',
458
+ operator: 'typeof',
459
+ argument: expressionOfKey(root, key),
460
+ prefix: true,
461
+ ...etc(),
462
+ },
463
+ right: stringLiteral('object'),
464
+ operator: '===',
465
+ ...etc(),
466
+ };
467
+ const notNull = {
468
+ type: 'BinaryExpression',
469
+ left: expressionOfKey(root, key),
470
+ right: nullLiteral(),
471
+ operator: '!==',
472
+ ...etc(),
473
+ };
474
+ return [typeofObject, notNull];
475
+ }
476
+ case 'prop-exists': {
477
+ // <propName> in <x>
478
+ const {key, propName} = condition;
479
+ const inObject: BinaryExpression = {
480
+ type: 'BinaryExpression',
481
+ left: stringLiteral(propName),
482
+ right: expressionOfKey(root, key),
483
+ operator: 'in',
484
+ ...etc(),
485
+ };
486
+ return [inObject];
487
+ }
488
+ case 'or': {
489
+ // <a> || <b> || ...
490
+ const {orConditions} = condition;
491
+ const tests = orConditions.map(conditions =>
492
+ conjunction(testsOfConditions(root, conditions)),
493
+ );
494
+ return [disjunction(tests)];
495
+ }
496
+ }
497
+ }
498
+
499
+ function testsOfConditions(
500
+ root: Expression,
501
+ conditions: Array<Condition>,
502
+ ): Array<Expression> {
503
+ return conditions.flatMap(condition => testsOfCondition(root, condition));
504
+ }
505
+
506
+ function statementsOfBindings(
507
+ root: Expression,
508
+ bindings: Array<Binding>,
509
+ ): Array<Statement> {
510
+ return bindings.map(binding => {
511
+ switch (binding.type) {
512
+ case 'id': {
513
+ // const <id> = <x>;
514
+ const {key, kind, id} = binding;
515
+ return variableDeclaration(kind, id, expressionOfKey(root, key));
516
+ }
517
+ case 'array-rest': {
518
+ // const <id> = <x>.slice(<exclude>);
519
+ const {key, kind, id, exclude} = binding;
520
+ const init = callExpression(
521
+ {
522
+ type: 'MemberExpression',
523
+ object: expressionOfKey(root, key),
524
+ property: ident('slice'),
525
+ computed: false,
526
+ optional: false,
527
+ ...etc(),
528
+ },
529
+ [numberLiteral(exclude)],
530
+ );
531
+ return variableDeclaration(kind, id, init);
532
+ }
533
+ case 'object-rest': {
534
+ // const {a: _, b: _, ...<id>} = <x>;
535
+ const {key, kind, id, exclude} = binding;
536
+ const destructuring: ObjectPattern = {
537
+ type: 'ObjectPattern',
538
+ properties: exclude
539
+ .map(prop =>
540
+ prop.type === 'Identifier'
541
+ ? {
542
+ type: 'Property',
543
+ key: shallowCloneNode(prop),
544
+ value: genIdent(),
545
+ kind: 'init',
546
+ computed: false,
547
+ method: false,
548
+ shorthand: false,
549
+ ...etc(),
550
+ parent: EMPTY_PARENT,
551
+ }
552
+ : {
553
+ type: 'Property',
554
+ key: shallowCloneNode(prop),
555
+ value: genIdent(),
556
+ kind: 'init',
557
+ computed: true,
558
+ method: false,
559
+ shorthand: false,
560
+ ...etc(),
561
+ parent: EMPTY_PARENT,
562
+ },
563
+ )
564
+ .concat({
565
+ type: 'RestElement',
566
+ argument: id,
567
+ ...etc(),
568
+ }),
569
+ typeAnnotation: null,
570
+ ...etc(),
571
+ };
572
+ return variableDeclaration(
573
+ kind,
574
+ destructuring,
575
+ expressionOfKey(root, key),
576
+ );
577
+ }
578
+ }
579
+ });
580
+ }
581
+
582
+ /**
583
+ * For throwing an error if no cases are matched.
584
+ */
585
+ const fallthroughErrorMsgText = `Match: No case succesfully matched. Make exhaustive or add a wildcard case using '_'.`;
586
+ function fallthroughErrorMsg(value: Expression): Expression {
587
+ return {
588
+ type: 'BinaryExpression',
589
+ operator: '+',
590
+ left: stringLiteral(`${fallthroughErrorMsgText} Argument: `),
591
+ right: value,
592
+ ...etc(),
593
+ };
594
+ }
595
+ function fallthroughError(value: Expression): Statement {
596
+ return throwStatement(fallthroughErrorMsg(value));
597
+ }
598
+
599
+ /**
600
+ * If the argument has no side-effects (ignoring getters). Either an identifier
601
+ * or member expression with identifier root and non-computed/literal properties.
602
+ */
603
+ function calculateSimpleArgument(node: Expression | Super): boolean {
604
+ switch (node.type) {
605
+ case 'Identifier':
606
+ case 'Super':
607
+ return true;
608
+ case 'MemberExpression': {
609
+ const {object, property, computed} = node;
610
+ if (computed && property.type !== 'Literal') {
611
+ return false;
612
+ }
613
+ return calculateSimpleArgument(object);
614
+ }
615
+ default:
616
+ return false;
617
+ }
618
+ }
619
+
620
+ /**
621
+ * Analyze the match cases and return information we will use to build the result.
622
+ */
623
+ type CaseAnalysis<T> = {
624
+ +conditions: Array<Condition>,
625
+ +bindings: Array<Binding>,
626
+ +guard: Expression | null,
627
+ +body: T,
628
+ };
629
+
630
+ interface MatchCase<T> {
631
+ +pattern: MatchPattern;
632
+ +guard: Expression | null;
633
+ +body: T;
634
+ }
635
+
636
+ function analyzeCases<T>(cases: $ReadOnlyArray<MatchCase<T>>): {
637
+ hasBindings: boolean,
638
+ hasWildcard: boolean,
639
+ analyses: Array<CaseAnalysis<T>>,
640
+ } {
641
+ let hasBindings = false;
642
+ let hasWildcard = false;
643
+ const analyses: Array<CaseAnalysis<T>> = [];
644
+ for (let i = 0; i < cases.length; i++) {
645
+ const {pattern, guard, body} = cases[i];
646
+ const {conditions, bindings} = analyzePattern(
647
+ pattern,
648
+ [],
649
+ new Set<string>(),
650
+ );
651
+ hasBindings = hasBindings || bindings.length > 0;
652
+ analyses.push({
653
+ conditions,
654
+ bindings,
655
+ guard,
656
+ body,
657
+ });
658
+ // This case catches everything, no reason to continue.
659
+ if (conditions.length === 0 && guard == null) {
660
+ hasWildcard = true;
661
+ break;
662
+ }
663
+ }
664
+ return {
665
+ hasBindings,
666
+ hasWildcard,
667
+ analyses,
668
+ };
669
+ }
670
+
671
+ /**
672
+ * Match expression transform entry point.
673
+ */
674
+ function mapMatchExpression(node: MatchExpression): Expression {
675
+ const {argument, cases} = node;
676
+ const {hasBindings, hasWildcard, analyses} = analyzeCases(cases);
677
+
678
+ const isSimpleArgument = calculateSimpleArgument(argument);
679
+ const genRoot: Identifier | null = !isSimpleArgument ? genIdent() : null;
680
+ const root: Expression = genRoot == null ? argument : genRoot;
681
+
682
+ // No bindings and a simple argument means we can use nested conditional
683
+ // expressions.
684
+ if (!hasBindings && isSimpleArgument) {
685
+ const wildcardAnalaysis = hasWildcard ? analyses.pop() : null;
686
+ const lastBody =
687
+ wildcardAnalaysis != null
688
+ ? wildcardAnalaysis.body
689
+ : iife([fallthroughError(shallowCloneNode(root))]);
690
+
691
+ return analyses.reverse().reduce((acc, analysis) => {
692
+ const {conditions, guard, body} = analysis;
693
+ const tests = testsOfConditions(root, conditions);
694
+ if (guard != null) {
695
+ tests.push(guard);
696
+ }
697
+ // <tests> ? <body> : <acc>
698
+ return {
699
+ type: 'ConditionalExpression',
700
+ test: conjunction(tests),
701
+ consequent: body,
702
+ alternate: acc,
703
+ ...etc(),
704
+ };
705
+ }, lastBody);
706
+ }
707
+
708
+ // There are bindings, so we produce an immediately invoked arrow expression.
709
+
710
+ // If the original argument is simple, no need for a new variable.
711
+ const statements: Array<Statement> = analyses.map(
712
+ ({conditions, bindings, guard, body}) => {
713
+ const returnNode = {
714
+ type: 'ReturnStatement',
715
+ argument: body,
716
+ ...etc(),
717
+ };
718
+ // If we have a guard, then we use a nested if statement
719
+ // `if (<guard>) return <body>`
720
+ const bodyNode: Statement =
721
+ guard == null
722
+ ? returnNode
723
+ : {
724
+ type: 'IfStatement',
725
+ test: guard,
726
+ consequent: returnNode,
727
+ ...etc(),
728
+ };
729
+ const bindingNodes = statementsOfBindings(root, bindings);
730
+ const caseBody: Array<Statement> = bindingNodes.concat(bodyNode);
731
+ if (conditions.length > 0) {
732
+ const tests = testsOfConditions(root, conditions);
733
+ return {
734
+ type: 'IfStatement',
735
+ test: conjunction(tests),
736
+ consequent: {
737
+ type: 'BlockStatement',
738
+ body: caseBody,
739
+ ...etc(),
740
+ },
741
+ ...etc(),
742
+ };
743
+ } else {
744
+ // No conditions, so no if statement
745
+ if (bindingNodes.length > 0) {
746
+ // Bindings require a block to introduce a new scope
747
+ return {
748
+ type: 'BlockStatement',
749
+ body: caseBody,
750
+ ...etc(),
751
+ };
752
+ } else {
753
+ return bodyNode;
754
+ }
755
+ }
756
+ },
757
+ );
758
+
759
+ if (!hasWildcard) {
760
+ statements.push(fallthroughError(shallowCloneNode(root)));
761
+ }
762
+
763
+ const [params, args] = genRoot == null ? [[], []] : [[genRoot], [argument]];
764
+
765
+ // `((<params>) => { ... })(<args>)`, or
766
+ // `(() => { ... })()` if is simple argument.
767
+ return iife(statements, params, args);
768
+ }
769
+
770
+ /**
771
+ * Match statement transform entry point.
772
+ */
773
+ function mapMatchStatement(node: MatchStatement): Statement {
774
+ const {argument, cases} = node;
775
+ const {hasWildcard, analyses} = analyzeCases(cases);
776
+
777
+ const topLabel: Identifier = genIdent();
778
+ const isSimpleArgument = calculateSimpleArgument(argument);
779
+ const genRoot: Identifier | null = !isSimpleArgument ? genIdent() : null;
780
+ const root: Expression = genRoot == null ? argument : genRoot;
781
+
782
+ const statements: Array<Statement> = [];
783
+ if (genRoot != null) {
784
+ statements.push(variableDeclaration('const', genRoot, argument));
785
+ }
786
+ analyses.forEach(({conditions, bindings, guard, body}) => {
787
+ const breakNode: BreakStatement = {
788
+ type: 'BreakStatement',
789
+ label: shallowCloneNode(topLabel),
790
+ ...etc(),
791
+ };
792
+ const bodyStatements = body.body.concat(breakNode);
793
+ // If we have a guard, then we use a nested if statement
794
+ // `if (<guard>) return <body>`
795
+ const guardedBodyStatements: Array<Statement> =
796
+ guard == null
797
+ ? bodyStatements
798
+ : [
799
+ {
800
+ type: 'IfStatement',
801
+ test: guard,
802
+ consequent: {
803
+ type: 'BlockStatement',
804
+ body: bodyStatements,
805
+ ...etc(),
806
+ },
807
+ ...etc(),
808
+ },
809
+ ];
810
+ const bindingNodes = statementsOfBindings(root, bindings);
811
+ const caseBody: Array<Statement> = bindingNodes.concat(
812
+ guardedBodyStatements,
813
+ );
814
+ if (conditions.length > 0) {
815
+ const tests = testsOfConditions(root, conditions);
816
+ statements.push({
817
+ type: 'IfStatement',
818
+ test: conjunction(tests),
819
+ consequent: {
820
+ type: 'BlockStatement',
821
+ body: caseBody,
822
+ ...etc(),
823
+ },
824
+ ...etc(),
825
+ });
826
+ } else {
827
+ // No conditions, so no if statement
828
+ statements.push({
829
+ type: 'BlockStatement',
830
+ body: caseBody,
831
+ ...etc(),
832
+ });
833
+ }
834
+ });
835
+
836
+ if (!hasWildcard) {
837
+ statements.push(fallthroughError(shallowCloneNode(root)));
838
+ }
839
+
840
+ return {
841
+ type: 'LabeledStatement',
842
+ label: topLabel,
843
+ body: {
844
+ type: 'BlockStatement',
845
+ body: statements,
846
+ ...etc(),
847
+ },
848
+ ...etc(),
849
+ };
850
+ }
851
+
852
+ export function transformProgram(
853
+ program: Program,
854
+ _options: ParserOptions,
855
+ ): Program {
856
+ // Initialize so each file transformed starts freshly incrementing the
857
+ // variable name counter, and has its own usage tracking.
858
+ GenID = createGenID('m');
859
+ return SimpleTransform.transformProgram(program, {
860
+ transform(node: ESNode) {
861
+ switch (node.type) {
862
+ case 'MatchExpression': {
863
+ return mapMatchExpression(node);
864
+ }
865
+ case 'MatchStatement': {
866
+ return mapMatchStatement(node);
867
+ }
868
+ case 'Identifier': {
869
+ // A rudimentary check to avoid some collisions with our generated
870
+ // variable names. Ideally, we would have access a scope analyzer
871
+ // inside the transform instead.
872
+ if (GenID == null) {
873
+ throw Error(
874
+ 'GenID must be initialized at the start of the transform.',
875
+ );
876
+ }
877
+ GenID.addUsage(node.name);
878
+ return node;
879
+ }
880
+ default: {
881
+ return node;
882
+ }
883
+ }
884
+ },
885
+ });
886
+ }