hermes-parser 0.15.1 → 0.17.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,657 @@
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
+ /**
12
+ * This transform strips Flow types that are not supported past Babel 7.
13
+ *
14
+ * It is expected that all transforms create valid ESTree AST output. If
15
+ * the transform requires outputting Babel specific AST nodes then it
16
+ * should live in `ConvertESTreeToBabel.js`
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ import type {ParserOptions} from '../ParserOptions';
22
+ import type {
23
+ Program,
24
+ ESNode,
25
+ DeclareComponent,
26
+ DeclareVariable,
27
+ ComponentDeclaration,
28
+ FunctionDeclaration,
29
+ TypeAnnotation,
30
+ ComponentParameter,
31
+ SourceLocation,
32
+ Position,
33
+ ObjectPattern,
34
+ Identifier,
35
+ Range,
36
+ RestElement,
37
+ DestructuringObjectProperty,
38
+ VariableDeclaration,
39
+ ModuleDeclaration,
40
+ Statement,
41
+ } from 'hermes-estree';
42
+
43
+ import {SimpleTransform} from '../transform/SimpleTransform';
44
+ import {shallowCloneNode} from '../transform/astNodeMutationHelpers';
45
+ import {SimpleTraverser} from '../traverse/SimpleTraverser';
46
+ import {createSyntaxError} from '../utils/createSyntaxError';
47
+
48
+ const nodeWith = SimpleTransform.nodeWith;
49
+
50
+ // Rely on the mapper to fix up parent relationships.
51
+ const EMPTY_PARENT: $FlowFixMe = null;
52
+
53
+ function createDefaultPosition(): Position {
54
+ return {
55
+ line: 1,
56
+ column: 0,
57
+ };
58
+ }
59
+
60
+ function mapDeclareComponent(node: DeclareComponent): DeclareVariable {
61
+ return {
62
+ type: 'DeclareVariable',
63
+ id: nodeWith(node.id, {
64
+ typeAnnotation: {
65
+ type: 'TypeAnnotation',
66
+ typeAnnotation: {
67
+ type: 'AnyTypeAnnotation',
68
+ loc: node.loc,
69
+ range: node.range,
70
+ parent: EMPTY_PARENT,
71
+ },
72
+ loc: node.loc,
73
+ range: node.range,
74
+ parent: EMPTY_PARENT,
75
+ },
76
+ }),
77
+ kind: 'const',
78
+ loc: node.loc,
79
+ range: node.range,
80
+ parent: node.parent,
81
+ };
82
+ }
83
+
84
+ function getComponentParameterName(
85
+ paramName: ComponentParameter['name'],
86
+ ): string {
87
+ switch (paramName.type) {
88
+ case 'Identifier':
89
+ return paramName.name;
90
+ case 'Literal':
91
+ return paramName.value;
92
+ default:
93
+ throw createSyntaxError(
94
+ paramName,
95
+ `Unknown Component parameter name type of "${paramName.type}"`,
96
+ );
97
+ }
98
+ }
99
+
100
+ function createPropsTypeAnnotation(
101
+ loc: ?SourceLocation,
102
+ range: ?Range,
103
+ ): TypeAnnotation {
104
+ // Create empty loc for type annotation nodes
105
+ const createParamsTypeLoc = () => ({
106
+ loc: {
107
+ start: loc?.start != null ? loc.start : createDefaultPosition(),
108
+ end: loc?.end != null ? loc.end : createDefaultPosition(),
109
+ },
110
+ range: range ?? [0, 0],
111
+ parent: EMPTY_PARENT,
112
+ });
113
+
114
+ return {
115
+ type: 'TypeAnnotation',
116
+ typeAnnotation: {
117
+ type: 'GenericTypeAnnotation',
118
+ id: {
119
+ type: 'Identifier',
120
+ name: '$ReadOnly',
121
+ optional: false,
122
+ typeAnnotation: null,
123
+ ...createParamsTypeLoc(),
124
+ },
125
+ typeParameters: {
126
+ type: 'TypeParameterInstantiation',
127
+ params: [
128
+ {
129
+ type: 'ObjectTypeAnnotation',
130
+ callProperties: [],
131
+ properties: [],
132
+ indexers: [],
133
+ internalSlots: [],
134
+ exact: false,
135
+ inexact: true,
136
+ ...createParamsTypeLoc(),
137
+ },
138
+ ],
139
+ ...createParamsTypeLoc(),
140
+ },
141
+ ...createParamsTypeLoc(),
142
+ },
143
+ ...createParamsTypeLoc(),
144
+ };
145
+ }
146
+
147
+ function mapComponentParameters(
148
+ params: $ReadOnlyArray<ComponentParameter | RestElement>,
149
+ ): $ReadOnly<{
150
+ props: ?(ObjectPattern | Identifier),
151
+ ref: ?Identifier,
152
+ }> {
153
+ if (params.length === 0) {
154
+ return {props: null, ref: null};
155
+ }
156
+
157
+ // Optimize `component Foo(...props: Props) {}` to `function Foo(props: Props) {}
158
+ if (
159
+ params.length === 1 &&
160
+ params[0].type === 'RestElement' &&
161
+ (params[0].argument.type === 'Identifier' ||
162
+ params[0].argument.type === 'ObjectPattern')
163
+ ) {
164
+ const restElementArgument = params[0].argument;
165
+ return {
166
+ props: nodeWith(restElementArgument, {
167
+ typeAnnotation: createPropsTypeAnnotation(
168
+ restElementArgument.typeAnnotation?.loc,
169
+ restElementArgument.typeAnnotation?.range,
170
+ ),
171
+ }),
172
+ ref: null,
173
+ };
174
+ }
175
+
176
+ // Filter out any ref param and capture it's details.
177
+ let refParam = null;
178
+ const paramsWithoutRef = params.filter(param => {
179
+ if (
180
+ param.type === 'ComponentParameter' &&
181
+ getComponentParameterName(param.name) === 'ref'
182
+ ) {
183
+ refParam = param;
184
+ return false;
185
+ }
186
+
187
+ return true;
188
+ });
189
+
190
+ const propsProperties = paramsWithoutRef.map(mapComponentParameter);
191
+
192
+ let props = null;
193
+ if (propsProperties.length === 0) {
194
+ if (refParam == null) {
195
+ throw new Error(
196
+ 'TransformReactScriptForBabel: Invalid state, ref should always be set at this point if props are empty',
197
+ );
198
+ }
199
+ const emptyParamsLoc = {
200
+ start: refParam.loc.start,
201
+ end: refParam.loc.start,
202
+ };
203
+ const emptyParamsRange = [refParam.range[0], refParam.range[0]];
204
+ // no properties provided (must have had a single ref)
205
+ props = {
206
+ type: 'Identifier',
207
+ name: '_$$empty_props_placeholder$$',
208
+ optional: false,
209
+ typeAnnotation: createPropsTypeAnnotation(
210
+ emptyParamsLoc,
211
+ emptyParamsRange,
212
+ ),
213
+ loc: emptyParamsLoc,
214
+ range: emptyParamsRange,
215
+ parent: EMPTY_PARENT,
216
+ };
217
+ } else {
218
+ const lastPropsProperty = propsProperties[propsProperties.length - 1];
219
+ props = {
220
+ type: 'ObjectPattern',
221
+ properties: propsProperties,
222
+ typeAnnotation: createPropsTypeAnnotation(
223
+ {
224
+ start: lastPropsProperty.loc.end,
225
+ end: lastPropsProperty.loc.end,
226
+ },
227
+ [lastPropsProperty.range[1], lastPropsProperty.range[1]],
228
+ ),
229
+ loc: {
230
+ start: propsProperties[0].loc.start,
231
+ end: lastPropsProperty.loc.end,
232
+ },
233
+ range: [propsProperties[0].range[0], lastPropsProperty.range[1]],
234
+ parent: EMPTY_PARENT,
235
+ };
236
+ }
237
+
238
+ let ref = null;
239
+ if (refParam != null) {
240
+ const refType = refParam.local;
241
+ ref = {
242
+ type: 'Identifier',
243
+ name: 'ref',
244
+ optional: false,
245
+ typeAnnotation:
246
+ refType.type === 'AssignmentPattern'
247
+ ? refType.left.typeAnnotation
248
+ : refType.typeAnnotation,
249
+ loc: refParam.loc,
250
+ range: refParam.range,
251
+ parent: EMPTY_PARENT,
252
+ };
253
+ }
254
+
255
+ return {
256
+ props,
257
+ ref,
258
+ };
259
+ }
260
+
261
+ function mapComponentParameter(
262
+ param: ComponentParameter | RestElement,
263
+ ): DestructuringObjectProperty | RestElement {
264
+ switch (param.type) {
265
+ case 'RestElement': {
266
+ const a = nodeWith(param, {
267
+ typeAnnotation: null,
268
+ argument: nodeWith(param.argument, {typeAnnotation: null}),
269
+ });
270
+ return a;
271
+ }
272
+ case 'ComponentParameter': {
273
+ if (getComponentParameterName(param.name) === 'ref') {
274
+ throw createSyntaxError(
275
+ param,
276
+ 'Component parameters named "ref" are currently not supported',
277
+ );
278
+ }
279
+
280
+ let value;
281
+ if (param.local.type === 'AssignmentPattern') {
282
+ value = nodeWith(param.local, {
283
+ left: nodeWith(param.local.left, {
284
+ typeAnnotation: null,
285
+ optional: false,
286
+ }),
287
+ });
288
+ } else {
289
+ value = nodeWith(param.local, {
290
+ typeAnnotation: null,
291
+ optional: false,
292
+ });
293
+ }
294
+
295
+ // Shorthand params
296
+ if (
297
+ param.name.type === 'Identifier' &&
298
+ param.shorthand &&
299
+ (value.type === 'Identifier' || value.type === 'AssignmentPattern')
300
+ ) {
301
+ return {
302
+ type: 'Property',
303
+ key: param.name,
304
+ kind: 'init',
305
+ value,
306
+ method: false,
307
+ shorthand: true,
308
+ computed: false,
309
+ loc: param.loc,
310
+ range: param.range,
311
+ parent: EMPTY_PARENT,
312
+ };
313
+ }
314
+
315
+ // Complex params
316
+ return {
317
+ type: 'Property',
318
+ key: param.name,
319
+ kind: 'init',
320
+ value,
321
+ method: false,
322
+ shorthand: false,
323
+ computed: false,
324
+ loc: param.loc,
325
+ range: param.range,
326
+ parent: EMPTY_PARENT,
327
+ };
328
+ }
329
+ default: {
330
+ throw createSyntaxError(
331
+ param,
332
+ `Unknown Component parameter type of "${param.type}"`,
333
+ );
334
+ }
335
+ }
336
+ }
337
+
338
+ type ForwardRefDetails = {
339
+ forwardRefStatement: VariableDeclaration,
340
+ internalCompId: Identifier,
341
+ forwardRefCompId: Identifier,
342
+ };
343
+
344
+ function createForwardRefWrapper(
345
+ originalComponent: ComponentDeclaration,
346
+ ): ForwardRefDetails {
347
+ const internalCompId = {
348
+ type: 'Identifier',
349
+ name: `${originalComponent.id.name}_withRef`,
350
+ optional: false,
351
+ typeAnnotation: null,
352
+ loc: originalComponent.id.loc,
353
+ range: originalComponent.id.range,
354
+ parent: EMPTY_PARENT,
355
+ };
356
+ return {
357
+ forwardRefStatement: {
358
+ type: 'VariableDeclaration',
359
+ kind: 'const',
360
+ declarations: [
361
+ {
362
+ type: 'VariableDeclarator',
363
+ id: shallowCloneNode(originalComponent.id),
364
+ init: {
365
+ type: 'CallExpression',
366
+ callee: {
367
+ type: 'MemberExpression',
368
+ object: {
369
+ type: 'Identifier',
370
+ name: 'React',
371
+ optional: false,
372
+ typeAnnotation: null,
373
+ loc: originalComponent.loc,
374
+ range: originalComponent.range,
375
+ parent: EMPTY_PARENT,
376
+ },
377
+ property: {
378
+ type: 'Identifier',
379
+ name: 'forwardRef',
380
+ optional: false,
381
+ typeAnnotation: null,
382
+ loc: originalComponent.loc,
383
+ range: originalComponent.range,
384
+ parent: EMPTY_PARENT,
385
+ },
386
+ computed: false,
387
+ optional: false,
388
+ loc: originalComponent.loc,
389
+ range: originalComponent.range,
390
+ parent: EMPTY_PARENT,
391
+ },
392
+ arguments: [shallowCloneNode(internalCompId)],
393
+ typeArguments: null,
394
+ optional: false,
395
+ loc: originalComponent.loc,
396
+ range: originalComponent.range,
397
+ parent: EMPTY_PARENT,
398
+ },
399
+ loc: originalComponent.loc,
400
+ range: originalComponent.range,
401
+ parent: EMPTY_PARENT,
402
+ },
403
+ ],
404
+ loc: originalComponent.loc,
405
+ range: originalComponent.range,
406
+ parent: originalComponent.parent,
407
+ },
408
+ internalCompId: internalCompId,
409
+ forwardRefCompId: originalComponent.id,
410
+ };
411
+ }
412
+
413
+ function mapComponentDeclaration(node: ComponentDeclaration): {
414
+ comp: FunctionDeclaration,
415
+ forwardRefDetails: ?ForwardRefDetails,
416
+ } {
417
+ // Create empty loc for return type annotation nodes
418
+ const createRendersTypeLoc = () => ({
419
+ loc: {
420
+ start: node.body.loc.end,
421
+ end: node.body.loc.end,
422
+ },
423
+ range: [node.body.range[1], node.body.range[1]],
424
+ parent: EMPTY_PARENT,
425
+ });
426
+ const returnType: TypeAnnotation = {
427
+ type: 'TypeAnnotation',
428
+ typeAnnotation: {
429
+ type: 'GenericTypeAnnotation',
430
+ id: {
431
+ type: 'QualifiedTypeIdentifier',
432
+ qualification: {
433
+ type: 'Identifier',
434
+ name: 'React',
435
+ optional: false,
436
+ typeAnnotation: null,
437
+ ...createRendersTypeLoc(),
438
+ },
439
+ id: {
440
+ type: 'Identifier',
441
+ name: 'Node',
442
+ optional: false,
443
+ typeAnnotation: null,
444
+ ...createRendersTypeLoc(),
445
+ },
446
+ ...createRendersTypeLoc(),
447
+ },
448
+ typeParameters: null,
449
+ ...createRendersTypeLoc(),
450
+ },
451
+ ...createRendersTypeLoc(),
452
+ };
453
+
454
+ const {props, ref} = mapComponentParameters(node.params);
455
+
456
+ let forwardRefDetails: ?ForwardRefDetails = null;
457
+
458
+ if (ref != null) {
459
+ forwardRefDetails = createForwardRefWrapper(node);
460
+ }
461
+
462
+ const comp = {
463
+ type: 'FunctionDeclaration',
464
+ id:
465
+ forwardRefDetails != null
466
+ ? shallowCloneNode(forwardRefDetails.internalCompId)
467
+ : shallowCloneNode(node.id),
468
+ __componentDeclaration: true,
469
+ typeParameters: node.typeParameters,
470
+ params: props == null ? [] : ref == null ? [props] : [props, ref],
471
+ returnType,
472
+ body: node.body,
473
+ async: false,
474
+ generator: false,
475
+ predicate: null,
476
+ loc: node.loc,
477
+ range: node.range,
478
+ parent: node.parent,
479
+ };
480
+
481
+ return {comp, forwardRefDetails};
482
+ }
483
+
484
+ /**
485
+ * Scan a list of statements and return the position of the
486
+ * first statement that contains a reference to a given component
487
+ * or null of no references were found.
488
+ */
489
+ function scanForFirstComponentReference(
490
+ compName: string,
491
+ bodyList: Array<Statement | ModuleDeclaration>,
492
+ ): ?number {
493
+ for (let i = 0; i < bodyList.length; i++) {
494
+ const bodyNode = bodyList[i];
495
+ let referencePos = null;
496
+ SimpleTraverser.traverse(bodyNode, {
497
+ enter(node: ESNode) {
498
+ switch (node.type) {
499
+ case 'Identifier': {
500
+ if (node.name === compName) {
501
+ // We found a reference, record it and stop.
502
+ referencePos = i;
503
+ throw SimpleTraverser.Break;
504
+ }
505
+ }
506
+ }
507
+ },
508
+ leave(_node: ESNode) {},
509
+ });
510
+ if (referencePos != null) {
511
+ return referencePos;
512
+ }
513
+ }
514
+
515
+ return null;
516
+ }
517
+
518
+ function mapComponentDeclarationIntoList(
519
+ node: ComponentDeclaration,
520
+ newBody: Array<Statement | ModuleDeclaration>,
521
+ insertExport?: (Identifier | FunctionDeclaration) => ModuleDeclaration,
522
+ ) {
523
+ const {comp, forwardRefDetails} = mapComponentDeclaration(node);
524
+ if (forwardRefDetails != null) {
525
+ // Scan for references to our component.
526
+ const referencePos = scanForFirstComponentReference(
527
+ forwardRefDetails.forwardRefCompId.name,
528
+ newBody,
529
+ );
530
+
531
+ // If a reference is found insert the forwardRef statement before it (to simulate function hoisting).
532
+ if (referencePos != null) {
533
+ newBody.splice(referencePos, 0, forwardRefDetails.forwardRefStatement);
534
+ } else {
535
+ newBody.push(forwardRefDetails.forwardRefStatement);
536
+ }
537
+
538
+ newBody.push(comp);
539
+
540
+ if (insertExport != null) {
541
+ newBody.push(insertExport(forwardRefDetails.forwardRefCompId));
542
+ }
543
+ return;
544
+ }
545
+
546
+ newBody.push(insertExport != null ? insertExport(comp) : comp);
547
+ }
548
+
549
+ function mapStatementList(
550
+ stmts: $ReadOnlyArray<Statement | ModuleDeclaration>,
551
+ ) {
552
+ const newBody: Array<Statement | ModuleDeclaration> = [];
553
+ for (const node of stmts) {
554
+ switch (node.type) {
555
+ case 'ComponentDeclaration': {
556
+ mapComponentDeclarationIntoList(node, newBody);
557
+ break;
558
+ }
559
+ case 'ExportNamedDeclaration': {
560
+ if (node.declaration?.type === 'ComponentDeclaration') {
561
+ mapComponentDeclarationIntoList(
562
+ node.declaration,
563
+ newBody,
564
+ componentOrRef => {
565
+ switch (componentOrRef.type) {
566
+ case 'FunctionDeclaration': {
567
+ // No ref, so we can export the component directly.
568
+ return nodeWith(node, {declaration: componentOrRef});
569
+ }
570
+ case 'Identifier': {
571
+ // If a ref is inserted, we should just export that id.
572
+ return {
573
+ type: 'ExportNamedDeclaration',
574
+ declaration: null,
575
+ specifiers: [
576
+ {
577
+ type: 'ExportSpecifier',
578
+ exported: shallowCloneNode(componentOrRef),
579
+ local: shallowCloneNode(componentOrRef),
580
+ loc: node.loc,
581
+ range: node.range,
582
+ parent: EMPTY_PARENT,
583
+ },
584
+ ],
585
+ exportKind: 'value',
586
+ source: null,
587
+ loc: node.loc,
588
+ range: node.range,
589
+ parent: node.parent,
590
+ };
591
+ }
592
+ }
593
+ },
594
+ );
595
+ break;
596
+ }
597
+
598
+ newBody.push(node);
599
+ break;
600
+ }
601
+ case 'ExportDefaultDeclaration': {
602
+ if (node.declaration?.type === 'ComponentDeclaration') {
603
+ mapComponentDeclarationIntoList(
604
+ node.declaration,
605
+ newBody,
606
+ componentOrRef => nodeWith(node, {declaration: componentOrRef}),
607
+ );
608
+ break;
609
+ }
610
+
611
+ newBody.push(node);
612
+ break;
613
+ }
614
+ default: {
615
+ newBody.push(node);
616
+ }
617
+ }
618
+ }
619
+
620
+ return newBody;
621
+ }
622
+
623
+ export function transformProgram(
624
+ program: Program,
625
+ _options: ParserOptions,
626
+ ): Program {
627
+ return SimpleTransform.transformProgram(program, {
628
+ transform(node: ESNode) {
629
+ switch (node.type) {
630
+ case 'DeclareComponent': {
631
+ return mapDeclareComponent(node);
632
+ }
633
+ case 'Program':
634
+ case 'BlockStatement': {
635
+ return nodeWith(node, {body: mapStatementList(node.body)});
636
+ }
637
+ case 'SwitchCase': {
638
+ return nodeWith(node, {
639
+ /* $FlowExpectedError[incompatible-call] We know `mapStatementList` will
640
+ not return `ModuleDeclaration` nodes if it is not passed any */
641
+ consequent: mapStatementList(node.consequent),
642
+ });
643
+ }
644
+ case 'ComponentDeclaration': {
645
+ throw createSyntaxError(
646
+ node,
647
+ `Components must be defined at the top level of a module or within a ` +
648
+ `BlockStatement, instead got parent of "${node.parent?.type}".`,
649
+ );
650
+ }
651
+ default: {
652
+ return node;
653
+ }
654
+ }
655
+ },
656
+ });
657
+ }