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