hermes-estree 0.32.1 → 0.33.1

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