hermes-parser 0.25.1 → 0.27.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,913 @@
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
+ * Does an object property's pattern require a `prop-exists` condition added?
180
+ * If the pattern is a literal like `0`, then it's not required, since the `eq`
181
+ * condition implies the prop exists. However, if we could be doing an equality
182
+ * check against `undefined`, then it is required, since that will be true even
183
+ * if the property doesn't exist.
184
+ */
185
+ function needsPropExistsCond(pattern: MatchPattern): boolean {
186
+ switch (pattern.type) {
187
+ case 'MatchWildcardPattern':
188
+ case 'MatchBindingPattern':
189
+ case 'MatchIdentifierPattern':
190
+ case 'MatchMemberPattern':
191
+ return true;
192
+ case 'MatchLiteralPattern':
193
+ case 'MatchUnaryPattern':
194
+ case 'MatchObjectPattern':
195
+ case 'MatchArrayPattern':
196
+ return false;
197
+ case 'MatchAsPattern': {
198
+ const {pattern: asPattern} = pattern;
199
+ return needsPropExistsCond(asPattern);
200
+ }
201
+ case 'MatchOrPattern': {
202
+ const {patterns} = pattern;
203
+ return patterns.some(needsPropExistsCond);
204
+ }
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Analyzes a match pattern, and produced both the conditions and bindings
210
+ * produced by that pattern.
211
+ */
212
+ function analyzePattern(
213
+ pattern: MatchPattern,
214
+ key: Key,
215
+ seenBindingNames: Set<string>,
216
+ ): {
217
+ conditions: Array<Condition>,
218
+ bindings: Array<Binding>,
219
+ } {
220
+ switch (pattern.type) {
221
+ case 'MatchWildcardPattern': {
222
+ return {conditions: [], bindings: []};
223
+ }
224
+ case 'MatchLiteralPattern': {
225
+ const {literal} = pattern;
226
+ const condition: Condition = {type: 'eq', key, arg: literal};
227
+ return {conditions: [condition], bindings: []};
228
+ }
229
+ case 'MatchUnaryPattern': {
230
+ const {operator, argument, loc, range} = pattern;
231
+ if (argument.value === 0) {
232
+ // We haven't decided whether we will compare these using `===` or `Object.is`
233
+ throw createSyntaxError(
234
+ pattern,
235
+ `'+0' and '-0' are not yet supported in match unary patterns.`,
236
+ );
237
+ }
238
+ const arg: UnaryExpression = {
239
+ type: 'UnaryExpression',
240
+ operator,
241
+ argument,
242
+ prefix: true,
243
+ ...etc({loc, range}),
244
+ };
245
+ const condition: Condition = {type: 'eq', key, arg};
246
+ return {conditions: [condition], bindings: []};
247
+ }
248
+ case 'MatchIdentifierPattern': {
249
+ const {id} = pattern;
250
+ const condition: Condition =
251
+ id.name === 'NaN' ? {type: 'is-nan', key} : {type: 'eq', key, arg: id};
252
+ return {conditions: [condition], bindings: []};
253
+ }
254
+ case 'MatchMemberPattern': {
255
+ const arg = convertMemberPattern(pattern);
256
+ const condition: Condition = {type: 'eq', key, arg};
257
+ return {conditions: [condition], bindings: []};
258
+ }
259
+ case 'MatchBindingPattern': {
260
+ const {id, kind} = pattern;
261
+ checkDuplicateBindingName(seenBindingNames, pattern, id.name);
262
+ checkBindingKind(pattern, kind);
263
+ const binding: Binding = {type: 'id', key, kind, id};
264
+ return {conditions: [], bindings: [binding]};
265
+ }
266
+ case 'MatchAsPattern': {
267
+ const {pattern: asPattern, target} = pattern;
268
+ if (asPattern.type === 'MatchBindingPattern') {
269
+ throw createSyntaxError(
270
+ pattern,
271
+ `Match 'as' patterns are not allowed directly on binding patterns.`,
272
+ );
273
+ }
274
+ const {conditions, bindings} = analyzePattern(
275
+ asPattern,
276
+ key,
277
+ seenBindingNames,
278
+ );
279
+ const [id, kind] =
280
+ target.type === 'MatchBindingPattern'
281
+ ? [target.id, target.kind]
282
+ : [target, 'const'];
283
+ checkDuplicateBindingName(seenBindingNames, pattern, id.name);
284
+ checkBindingKind(pattern, kind);
285
+ const binding: Binding = {type: 'id', key, kind, id};
286
+ return {conditions, bindings: bindings.concat(binding)};
287
+ }
288
+ case 'MatchArrayPattern': {
289
+ const {elements, rest} = pattern;
290
+ const lengthOp = rest == null ? 'eq' : 'gte';
291
+ const conditions: Array<Condition> = [
292
+ {type: 'array', key, length: elements.length, lengthOp},
293
+ ];
294
+ const bindings: Array<Binding> = [];
295
+ elements.forEach((element, i) => {
296
+ const elementKey = key.concat(numberLiteral(i));
297
+ const {conditions: childConditions, bindings: childBindings} =
298
+ analyzePattern(element, elementKey, seenBindingNames);
299
+ conditions.push(...childConditions);
300
+ bindings.push(...childBindings);
301
+ });
302
+ if (rest != null && rest.argument != null) {
303
+ const {id, kind} = rest.argument;
304
+ checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
305
+ checkBindingKind(pattern, kind);
306
+ bindings.push({
307
+ type: 'array-rest',
308
+ key,
309
+ exclude: elements.length,
310
+ kind,
311
+ id,
312
+ });
313
+ }
314
+ return {conditions, bindings};
315
+ }
316
+ case 'MatchObjectPattern': {
317
+ const {properties, rest} = pattern;
318
+ const conditions: Array<Condition> = [{type: 'object', key}];
319
+ const bindings: Array<Binding> = [];
320
+ const objKeys: Array<Identifier | Literal> = [];
321
+ const seenNames = new Set<string>();
322
+ properties.forEach(prop => {
323
+ const {key: objKey, pattern: propPattern} = prop;
324
+ objKeys.push(objKey);
325
+ const name = objKeyToString(objKey);
326
+ if (seenNames.has(name)) {
327
+ throw createSyntaxError(
328
+ propPattern,
329
+ `Duplicate property name '${name}' in match object pattern.`,
330
+ );
331
+ }
332
+ seenNames.add(name);
333
+ const propKey: Key = key.concat(objKey);
334
+ if (needsPropExistsCond(propPattern)) {
335
+ conditions.push({
336
+ type: 'prop-exists',
337
+ key,
338
+ propName: name,
339
+ });
340
+ }
341
+ const {conditions: childConditions, bindings: childBindings} =
342
+ analyzePattern(propPattern, propKey, seenBindingNames);
343
+ conditions.push(...childConditions);
344
+ bindings.push(...childBindings);
345
+ });
346
+ if (rest != null && rest.argument != null) {
347
+ const {id, kind} = rest.argument;
348
+ checkDuplicateBindingName(seenBindingNames, rest.argument, id.name);
349
+ checkBindingKind(pattern, kind);
350
+ bindings.push({
351
+ type: 'object-rest',
352
+ key,
353
+ exclude: objKeys,
354
+ kind,
355
+ id,
356
+ });
357
+ }
358
+ return {conditions, bindings};
359
+ }
360
+ case 'MatchOrPattern': {
361
+ const {patterns} = pattern;
362
+ let hasWildcard = false;
363
+ const orConditions = patterns.map(subpattern => {
364
+ const {conditions, bindings} = analyzePattern(
365
+ subpattern,
366
+ key,
367
+ seenBindingNames,
368
+ );
369
+ if (bindings.length > 0) {
370
+ // We will implement this in the future.
371
+ throw createSyntaxError(
372
+ pattern,
373
+ `Bindings in match 'or' patterns are not yet supported.`,
374
+ );
375
+ }
376
+ if (conditions.length === 0) {
377
+ hasWildcard = true;
378
+ }
379
+ return conditions;
380
+ });
381
+ if (hasWildcard) {
382
+ return {conditions: [], bindings: []};
383
+ }
384
+ return {
385
+ conditions: [{type: 'or', orConditions}],
386
+ bindings: [],
387
+ };
388
+ }
389
+ }
390
+ }
391
+
392
+ function expressionOfKey(root: Expression, key: Key): Expression {
393
+ return key.reduce(
394
+ (acc, prop) =>
395
+ prop.type === 'Identifier'
396
+ ? {
397
+ type: 'MemberExpression',
398
+ object: acc,
399
+ property: shallowCloneNode(prop),
400
+ computed: false,
401
+ optional: false,
402
+ ...etc(),
403
+ }
404
+ : {
405
+ type: 'MemberExpression',
406
+ object: acc,
407
+ property: shallowCloneNode(prop),
408
+ computed: true,
409
+ optional: false,
410
+ ...etc(),
411
+ },
412
+ deepCloneNode(root),
413
+ );
414
+ }
415
+
416
+ function testsOfCondition(
417
+ root: Expression,
418
+ condition: Condition,
419
+ ): Array<Expression> {
420
+ switch (condition.type) {
421
+ case 'eq': {
422
+ // <x> === <arg>
423
+ const {key, arg} = condition;
424
+ return [
425
+ {
426
+ type: 'BinaryExpression',
427
+ left: expressionOfKey(root, key),
428
+ right: arg,
429
+ operator: '===',
430
+ ...etc(),
431
+ },
432
+ ];
433
+ }
434
+ case 'is-nan': {
435
+ // Number.isNaN(<x>)
436
+ const {key} = condition;
437
+ const callee: MemberExpression = {
438
+ type: 'MemberExpression',
439
+ object: ident('Number'),
440
+ property: ident('isNaN'),
441
+ computed: false,
442
+ optional: false,
443
+ ...etc(),
444
+ };
445
+ return [callExpression(callee, [expressionOfKey(root, key)])];
446
+ }
447
+ case 'array': {
448
+ // Array.isArray(<x>) && <x>.length === <length>
449
+ const {key, length, lengthOp} = condition;
450
+ const operator = lengthOp === 'eq' ? '===' : '>=';
451
+ const isArray = callExpression(
452
+ {
453
+ type: 'MemberExpression',
454
+ object: ident('Array'),
455
+ property: ident('isArray'),
456
+ computed: false,
457
+ optional: false,
458
+ ...etc(),
459
+ },
460
+ [expressionOfKey(root, key)],
461
+ );
462
+ const lengthCheck: BinaryExpression = {
463
+ type: 'BinaryExpression',
464
+ left: {
465
+ type: 'MemberExpression',
466
+ object: expressionOfKey(root, key),
467
+ property: ident('length'),
468
+ computed: false,
469
+ optional: false,
470
+ ...etc(),
471
+ },
472
+ right: numberLiteral(length),
473
+ operator,
474
+ ...etc(),
475
+ };
476
+ return [isArray, lengthCheck];
477
+ }
478
+ case 'object': {
479
+ // typeof <x> === 'object' && <x> !== null
480
+ const {key} = condition;
481
+ const typeofObject: BinaryExpression = {
482
+ type: 'BinaryExpression',
483
+ left: {
484
+ type: 'UnaryExpression',
485
+ operator: 'typeof',
486
+ argument: expressionOfKey(root, key),
487
+ prefix: true,
488
+ ...etc(),
489
+ },
490
+ right: stringLiteral('object'),
491
+ operator: '===',
492
+ ...etc(),
493
+ };
494
+ const notNull = {
495
+ type: 'BinaryExpression',
496
+ left: expressionOfKey(root, key),
497
+ right: nullLiteral(),
498
+ operator: '!==',
499
+ ...etc(),
500
+ };
501
+ return [typeofObject, notNull];
502
+ }
503
+ case 'prop-exists': {
504
+ // <propName> in <x>
505
+ const {key, propName} = condition;
506
+ const inObject: BinaryExpression = {
507
+ type: 'BinaryExpression',
508
+ left: stringLiteral(propName),
509
+ right: expressionOfKey(root, key),
510
+ operator: 'in',
511
+ ...etc(),
512
+ };
513
+ return [inObject];
514
+ }
515
+ case 'or': {
516
+ // <a> || <b> || ...
517
+ const {orConditions} = condition;
518
+ const tests = orConditions.map(conditions =>
519
+ conjunction(testsOfConditions(root, conditions)),
520
+ );
521
+ return [disjunction(tests)];
522
+ }
523
+ }
524
+ }
525
+
526
+ function testsOfConditions(
527
+ root: Expression,
528
+ conditions: Array<Condition>,
529
+ ): Array<Expression> {
530
+ return conditions.flatMap(condition => testsOfCondition(root, condition));
531
+ }
532
+
533
+ function statementsOfBindings(
534
+ root: Expression,
535
+ bindings: Array<Binding>,
536
+ ): Array<Statement> {
537
+ return bindings.map(binding => {
538
+ switch (binding.type) {
539
+ case 'id': {
540
+ // const <id> = <x>;
541
+ const {key, kind, id} = binding;
542
+ return variableDeclaration(kind, id, expressionOfKey(root, key));
543
+ }
544
+ case 'array-rest': {
545
+ // const <id> = <x>.slice(<exclude>);
546
+ const {key, kind, id, exclude} = binding;
547
+ const init = callExpression(
548
+ {
549
+ type: 'MemberExpression',
550
+ object: expressionOfKey(root, key),
551
+ property: ident('slice'),
552
+ computed: false,
553
+ optional: false,
554
+ ...etc(),
555
+ },
556
+ [numberLiteral(exclude)],
557
+ );
558
+ return variableDeclaration(kind, id, init);
559
+ }
560
+ case 'object-rest': {
561
+ // const {a: _, b: _, ...<id>} = <x>;
562
+ const {key, kind, id, exclude} = binding;
563
+ const destructuring: ObjectPattern = {
564
+ type: 'ObjectPattern',
565
+ properties: exclude
566
+ .map(prop =>
567
+ prop.type === 'Identifier'
568
+ ? {
569
+ type: 'Property',
570
+ key: shallowCloneNode(prop),
571
+ value: genIdent(),
572
+ kind: 'init',
573
+ computed: false,
574
+ method: false,
575
+ shorthand: false,
576
+ ...etc(),
577
+ parent: EMPTY_PARENT,
578
+ }
579
+ : {
580
+ type: 'Property',
581
+ key: shallowCloneNode(prop),
582
+ value: genIdent(),
583
+ kind: 'init',
584
+ computed: true,
585
+ method: false,
586
+ shorthand: false,
587
+ ...etc(),
588
+ parent: EMPTY_PARENT,
589
+ },
590
+ )
591
+ .concat({
592
+ type: 'RestElement',
593
+ argument: id,
594
+ ...etc(),
595
+ }),
596
+ typeAnnotation: null,
597
+ ...etc(),
598
+ };
599
+ return variableDeclaration(
600
+ kind,
601
+ destructuring,
602
+ expressionOfKey(root, key),
603
+ );
604
+ }
605
+ }
606
+ });
607
+ }
608
+
609
+ /**
610
+ * For throwing an error if no cases are matched.
611
+ */
612
+ const fallthroughErrorMsgText = `Match: No case succesfully matched. Make exhaustive or add a wildcard case using '_'.`;
613
+ function fallthroughErrorMsg(value: Expression): Expression {
614
+ return {
615
+ type: 'BinaryExpression',
616
+ operator: '+',
617
+ left: stringLiteral(`${fallthroughErrorMsgText} Argument: `),
618
+ right: value,
619
+ ...etc(),
620
+ };
621
+ }
622
+ function fallthroughError(value: Expression): Statement {
623
+ return throwStatement(fallthroughErrorMsg(value));
624
+ }
625
+
626
+ /**
627
+ * If the argument has no side-effects (ignoring getters). Either an identifier
628
+ * or member expression with identifier root and non-computed/literal properties.
629
+ */
630
+ function calculateSimpleArgument(node: Expression | Super): boolean {
631
+ switch (node.type) {
632
+ case 'Identifier':
633
+ case 'Super':
634
+ return true;
635
+ case 'MemberExpression': {
636
+ const {object, property, computed} = node;
637
+ if (computed && property.type !== 'Literal') {
638
+ return false;
639
+ }
640
+ return calculateSimpleArgument(object);
641
+ }
642
+ default:
643
+ return false;
644
+ }
645
+ }
646
+
647
+ /**
648
+ * Analyze the match cases and return information we will use to build the result.
649
+ */
650
+ type CaseAnalysis<T> = {
651
+ +conditions: Array<Condition>,
652
+ +bindings: Array<Binding>,
653
+ +guard: Expression | null,
654
+ +body: T,
655
+ };
656
+
657
+ interface MatchCase<T> {
658
+ +pattern: MatchPattern;
659
+ +guard: Expression | null;
660
+ +body: T;
661
+ }
662
+
663
+ function analyzeCases<T>(cases: $ReadOnlyArray<MatchCase<T>>): {
664
+ hasBindings: boolean,
665
+ hasWildcard: boolean,
666
+ analyses: Array<CaseAnalysis<T>>,
667
+ } {
668
+ let hasBindings = false;
669
+ let hasWildcard = false;
670
+ const analyses: Array<CaseAnalysis<T>> = [];
671
+ for (let i = 0; i < cases.length; i++) {
672
+ const {pattern, guard, body} = cases[i];
673
+ const {conditions, bindings} = analyzePattern(
674
+ pattern,
675
+ [],
676
+ new Set<string>(),
677
+ );
678
+ hasBindings = hasBindings || bindings.length > 0;
679
+ analyses.push({
680
+ conditions,
681
+ bindings,
682
+ guard,
683
+ body,
684
+ });
685
+ // This case catches everything, no reason to continue.
686
+ if (conditions.length === 0 && guard == null) {
687
+ hasWildcard = true;
688
+ break;
689
+ }
690
+ }
691
+ return {
692
+ hasBindings,
693
+ hasWildcard,
694
+ analyses,
695
+ };
696
+ }
697
+
698
+ /**
699
+ * Match expression transform entry point.
700
+ */
701
+ function mapMatchExpression(node: MatchExpression): Expression {
702
+ const {argument, cases} = node;
703
+ const {hasBindings, hasWildcard, analyses} = analyzeCases(cases);
704
+
705
+ const isSimpleArgument = calculateSimpleArgument(argument);
706
+ const genRoot: Identifier | null = !isSimpleArgument ? genIdent() : null;
707
+ const root: Expression = genRoot == null ? argument : genRoot;
708
+
709
+ // No bindings and a simple argument means we can use nested conditional
710
+ // expressions.
711
+ if (!hasBindings && isSimpleArgument) {
712
+ const wildcardAnalaysis = hasWildcard ? analyses.pop() : null;
713
+ const lastBody =
714
+ wildcardAnalaysis != null
715
+ ? wildcardAnalaysis.body
716
+ : iife([fallthroughError(shallowCloneNode(root))]);
717
+
718
+ return analyses.reverse().reduce((acc, analysis) => {
719
+ const {conditions, guard, body} = analysis;
720
+ const tests = testsOfConditions(root, conditions);
721
+ if (guard != null) {
722
+ tests.push(guard);
723
+ }
724
+ // <tests> ? <body> : <acc>
725
+ return {
726
+ type: 'ConditionalExpression',
727
+ test: conjunction(tests),
728
+ consequent: body,
729
+ alternate: acc,
730
+ ...etc(),
731
+ };
732
+ }, lastBody);
733
+ }
734
+
735
+ // There are bindings, so we produce an immediately invoked arrow expression.
736
+
737
+ // If the original argument is simple, no need for a new variable.
738
+ const statements: Array<Statement> = analyses.map(
739
+ ({conditions, bindings, guard, body}) => {
740
+ const returnNode = {
741
+ type: 'ReturnStatement',
742
+ argument: body,
743
+ ...etc(),
744
+ };
745
+ // If we have a guard, then we use a nested if statement
746
+ // `if (<guard>) return <body>`
747
+ const bodyNode: Statement =
748
+ guard == null
749
+ ? returnNode
750
+ : {
751
+ type: 'IfStatement',
752
+ test: guard,
753
+ consequent: returnNode,
754
+ ...etc(),
755
+ };
756
+ const bindingNodes = statementsOfBindings(root, bindings);
757
+ const caseBody: Array<Statement> = bindingNodes.concat(bodyNode);
758
+ if (conditions.length > 0) {
759
+ const tests = testsOfConditions(root, conditions);
760
+ return {
761
+ type: 'IfStatement',
762
+ test: conjunction(tests),
763
+ consequent: {
764
+ type: 'BlockStatement',
765
+ body: caseBody,
766
+ ...etc(),
767
+ },
768
+ ...etc(),
769
+ };
770
+ } else {
771
+ // No conditions, so no if statement
772
+ if (bindingNodes.length > 0) {
773
+ // Bindings require a block to introduce a new scope
774
+ return {
775
+ type: 'BlockStatement',
776
+ body: caseBody,
777
+ ...etc(),
778
+ };
779
+ } else {
780
+ return bodyNode;
781
+ }
782
+ }
783
+ },
784
+ );
785
+
786
+ if (!hasWildcard) {
787
+ statements.push(fallthroughError(shallowCloneNode(root)));
788
+ }
789
+
790
+ const [params, args] = genRoot == null ? [[], []] : [[genRoot], [argument]];
791
+
792
+ // `((<params>) => { ... })(<args>)`, or
793
+ // `(() => { ... })()` if is simple argument.
794
+ return iife(statements, params, args);
795
+ }
796
+
797
+ /**
798
+ * Match statement transform entry point.
799
+ */
800
+ function mapMatchStatement(node: MatchStatement): Statement {
801
+ const {argument, cases} = node;
802
+ const {hasWildcard, analyses} = analyzeCases(cases);
803
+
804
+ const topLabel: Identifier = genIdent();
805
+ const isSimpleArgument = calculateSimpleArgument(argument);
806
+ const genRoot: Identifier | null = !isSimpleArgument ? genIdent() : null;
807
+ const root: Expression = genRoot == null ? argument : genRoot;
808
+
809
+ const statements: Array<Statement> = [];
810
+ if (genRoot != null) {
811
+ statements.push(variableDeclaration('const', genRoot, argument));
812
+ }
813
+ analyses.forEach(({conditions, bindings, guard, body}) => {
814
+ const breakNode: BreakStatement = {
815
+ type: 'BreakStatement',
816
+ label: shallowCloneNode(topLabel),
817
+ ...etc(),
818
+ };
819
+ const bodyStatements = body.body.concat(breakNode);
820
+ // If we have a guard, then we use a nested if statement
821
+ // `if (<guard>) return <body>`
822
+ const guardedBodyStatements: Array<Statement> =
823
+ guard == null
824
+ ? bodyStatements
825
+ : [
826
+ {
827
+ type: 'IfStatement',
828
+ test: guard,
829
+ consequent: {
830
+ type: 'BlockStatement',
831
+ body: bodyStatements,
832
+ ...etc(),
833
+ },
834
+ ...etc(),
835
+ },
836
+ ];
837
+ const bindingNodes = statementsOfBindings(root, bindings);
838
+ const caseBody: Array<Statement> = bindingNodes.concat(
839
+ guardedBodyStatements,
840
+ );
841
+ if (conditions.length > 0) {
842
+ const tests = testsOfConditions(root, conditions);
843
+ statements.push({
844
+ type: 'IfStatement',
845
+ test: conjunction(tests),
846
+ consequent: {
847
+ type: 'BlockStatement',
848
+ body: caseBody,
849
+ ...etc(),
850
+ },
851
+ ...etc(),
852
+ });
853
+ } else {
854
+ // No conditions, so no if statement
855
+ statements.push({
856
+ type: 'BlockStatement',
857
+ body: caseBody,
858
+ ...etc(),
859
+ });
860
+ }
861
+ });
862
+
863
+ if (!hasWildcard) {
864
+ statements.push(fallthroughError(shallowCloneNode(root)));
865
+ }
866
+
867
+ return {
868
+ type: 'LabeledStatement',
869
+ label: topLabel,
870
+ body: {
871
+ type: 'BlockStatement',
872
+ body: statements,
873
+ ...etc(),
874
+ },
875
+ ...etc(),
876
+ };
877
+ }
878
+
879
+ export function transformProgram(
880
+ program: Program,
881
+ _options: ParserOptions,
882
+ ): Program {
883
+ // Initialize so each file transformed starts freshly incrementing the
884
+ // variable name counter, and has its own usage tracking.
885
+ GenID = createGenID('m');
886
+ return SimpleTransform.transformProgram(program, {
887
+ transform(node: ESNode) {
888
+ switch (node.type) {
889
+ case 'MatchExpression': {
890
+ return mapMatchExpression(node);
891
+ }
892
+ case 'MatchStatement': {
893
+ return mapMatchStatement(node);
894
+ }
895
+ case 'Identifier': {
896
+ // A rudimentary check to avoid some collisions with our generated
897
+ // variable names. Ideally, we would have access a scope analyzer
898
+ // inside the transform instead.
899
+ if (GenID == null) {
900
+ throw Error(
901
+ 'GenID must be initialized at the start of the transform.',
902
+ );
903
+ }
904
+ GenID.addUsage(node.name);
905
+ return node;
906
+ }
907
+ default: {
908
+ return node;
909
+ }
910
+ }
911
+ },
912
+ });
913
+ }