This repository has been archived by the owner on Jan 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
convert.ts
2621 lines (2336 loc) · 76.6 KB
/
convert.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview Converts TypeScript AST into ESTree format.
* @author Nicholas C. Zakas
* @author James Henry <https://github.com/JamesHenry>
* @copyright jQuery Foundation and other contributors, https://jquery.org/
* MIT License
*/
import ts from 'typescript';
import {
canContainDirective,
createError,
getLoc,
getLocFor,
findNextToken,
convertToken,
hasModifier,
fixExports,
getTSNodeAccessibility,
getTextForTokenKind,
isJSXToken,
isComputedProperty,
isESTreeClassMember,
isComma,
getBinaryExpressionType,
isOptional,
findFirstMatchingToken,
unescapeStringLiteralText,
getDeclarationKind,
getLastModifier
} from './node-utils';
import { AST_NODE_TYPES } from './ast-node-types';
import { ESTreeNode } from './temp-types-based-on-js-source';
import { TSNode } from './ts-nodes';
const SyntaxKind = ts.SyntaxKind;
let esTreeNodeToTSNodeMap = new WeakMap();
let tsNodeToESTreeNodeMap = new WeakMap();
export function resetASTMaps() {
esTreeNodeToTSNodeMap = new WeakMap();
tsNodeToESTreeNodeMap = new WeakMap();
}
export function getASTMaps() {
return { esTreeNodeToTSNodeMap, tsNodeToESTreeNodeMap };
}
interface ConvertAdditionalOptions {
errorOnUnknownASTType: boolean;
useJSXTextNode: boolean;
shouldProvideParserServices: boolean;
}
interface ConvertConfig {
node: ts.Node;
parent?: ts.Node | null;
inTypeMode?: boolean;
allowPattern?: boolean;
ast: ts.SourceFile;
additionalOptions: ConvertAdditionalOptions;
}
/**
* Extends and formats a given error object
* @param {Object} error the error object
* @returns {Object} converted error object
*/
export function convertError(error: any) {
return createError(
error.file,
error.start,
error.message || error.messageText
);
}
/**
* Converts a TypeScript node into an ESTree node
* @param {Object} config configuration options for the conversion
* @param {TSNode} config.node the ts.Node
* @param {ts.Node} config.parent the parent ts.Node
* @param {ts.SourceFile} config.ast the full TypeScript AST
* @param {Object} config.additionalOptions additional options for the conversion
* @returns {ESTreeNode|null} the converted ESTreeNode
*/
export default function convert(config: ConvertConfig): ESTreeNode | null {
const node: TSNode = config.node as TSNode;
const parent = config.parent;
const ast = config.ast;
const additionalOptions = config.additionalOptions || {};
/**
* Exit early for null and undefined
*/
if (!node) {
return null;
}
/**
* Create a new ESTree node
*/
let result: ESTreeNode = {
type: '' as AST_NODE_TYPES,
range: [node.getStart(ast), node.end],
loc: getLoc(node, ast)
};
function converter(
child?: ts.Node,
inTypeMode?: boolean,
allowPattern?: boolean
): ESTreeNode | null {
if (!child) {
return null;
}
return convert({
node: child,
parent: node,
inTypeMode,
allowPattern,
ast,
additionalOptions
});
}
/**
* Converts a TypeScript node into an ESTree node.
* @param {ts.Node} child the child ts.Node
* @returns {ESTreeNode|null} the converted ESTree node
*/
function convertPattern(child?: ts.Node): ESTreeNode | null {
return converter(child, config.inTypeMode, true);
}
/**
* Converts a TypeScript node into an ESTree node.
* @param {ts.Node} child the child ts.Node
* @returns {ESTreeNode|null} the converted ESTree node
*/
function convertChild(child?: ts.Node): ESTreeNode | null {
return converter(child, config.inTypeMode, false);
}
/**
* Converts a TypeScript node into an ESTree node.
* @param {ts.Node} child the child ts.Node
* @returns {ESTreeNode|null} the converted ESTree node
*/
function convertChildType(child?: ts.Node): ESTreeNode | null {
return converter(child, true, false);
}
/**
* Converts a child into a type annotation. This creates an intermediary
* TypeAnnotation node to match what Flow does.
* @param {ts.TypeNode} child The TypeScript AST node to convert.
* @returns {ESTreeNode} The type annotation node.
*/
function convertTypeAnnotation(child: ts.TypeNode): ESTreeNode {
const annotation = convertChildType(child);
// in FunctionType and ConstructorType typeAnnotation has 2 characters `=>` and in other places is just colon
const offset =
node.kind === SyntaxKind.FunctionType ||
node.kind === SyntaxKind.ConstructorType
? 2
: 1;
const annotationStartCol = child.getFullStart() - offset;
const loc = getLocFor(annotationStartCol, child.end, ast);
return {
type: AST_NODE_TYPES.TSTypeAnnotation,
loc,
range: [annotationStartCol, child.end],
typeAnnotation: annotation
};
}
/**
* Coverts body Nodes and add directive field to StringLiterals
* @param {ts.NodeArray<ts.Statement>} nodes of ts.Node
* @returns {ESTreeNode[]} Array of body statements
*/
function convertBodyExpressions(
nodes: ts.NodeArray<ts.Statement>
): ESTreeNode[] {
// directives has to be unique, if directive is registered twice pick only first one
const unique: string[] = [];
const allowDirectives = canContainDirective(node);
return (
nodes
.map(statement => {
const child = convertChild(statement);
if (
allowDirectives &&
child &&
child.expression &&
ts.isExpressionStatement(statement) &&
ts.isStringLiteral(statement.expression)
) {
const raw = child.expression.raw!;
if (!unique.includes(raw)) {
child.directive = raw.slice(1, -1);
unique.push(raw);
}
}
return child!; // child can be null but it's filtered below
})
// filter out unknown nodes for now
.filter(statement => statement)
);
}
/**
* Converts a ts.Node's typeArguments ts.NodeArray to a flow-like typeParameters node
* @param {ts.NodeArray<any>} typeArguments ts.Node typeArguments
* @returns {ESTreeNode} TypeParameterInstantiation node
*/
function convertTypeArgumentsToTypeParameters(
typeArguments: ts.NodeArray<any>
): ESTreeNode {
/**
* Even if typeArguments is an empty array, TypeScript sets a `pos` and `end`
* property on the array object so we can safely read the values here
*/
const start = typeArguments.pos - 1;
let end = typeArguments.end + 1;
if (typeArguments && typeArguments.length) {
const firstTypeArgument = typeArguments[0];
const typeArgumentsParent = firstTypeArgument.parent;
/**
* In the case of the parent being a CallExpression or a TypeReference we have to use
* slightly different logic to calculate the correct end position
*/
if (
typeArgumentsParent &&
(typeArgumentsParent.kind === SyntaxKind.CallExpression ||
typeArgumentsParent.kind === SyntaxKind.TypeReference)
) {
const lastTypeArgument = typeArguments[typeArguments.length - 1];
const greaterThanToken = findNextToken(lastTypeArgument, ast, ast);
end = greaterThanToken!.end;
}
}
return {
type: AST_NODE_TYPES.TSTypeParameterInstantiation,
range: [start, end],
loc: getLocFor(start, end, ast),
params: typeArguments.map(typeArgument => convertChildType(typeArgument))
};
}
/**
* Converts a ts.Node's typeParameters ts.ts.NodeArray to a flow-like TypeParameterDeclaration node
* @param {ts.NodeArray} typeParameters ts.Node typeParameters
* @returns {ESTreeNode} TypeParameterDeclaration node
*/
function convertTSTypeParametersToTypeParametersDeclaration(
typeParameters: ts.NodeArray<any>
): ESTreeNode {
const firstTypeParameter = typeParameters[0];
const lastTypeParameter = typeParameters[typeParameters.length - 1];
const greaterThanToken = findNextToken(lastTypeParameter, ast, ast);
return {
type: AST_NODE_TYPES.TSTypeParameterDeclaration,
range: [firstTypeParameter.pos - 1, greaterThanToken!.end],
loc: getLocFor(firstTypeParameter.pos - 1, greaterThanToken!.end, ast),
params: typeParameters.map(typeParameter =>
convertChildType(typeParameter)
)
};
}
/**
* Converts a child into a specified heritage node.
* @param {AST_NODE_TYPES} nodeType Type of node to be used
* @param {ts.ExpressionWithTypeArguments} child The TypeScript AST node to convert.
* @returns {ESTreeNode} The heritage node.
*/
function convertHeritageClause(
nodeType: AST_NODE_TYPES,
child: ts.ExpressionWithTypeArguments
): ESTreeNode {
const expression = convertChild(child.expression)!;
const classImplementsNode: ESTreeNode = {
type: nodeType,
loc: expression.loc,
range: expression.range,
expression
};
if (child.typeArguments && child.typeArguments.length) {
classImplementsNode.typeParameters = convertTypeArgumentsToTypeParameters(
child.typeArguments
);
}
return classImplementsNode;
}
/**
* Converts an array of ts.Node parameters into an array of ESTreeNode params
* @param {ts.Node[]} parameters An array of ts.Node params to be converted
* @returns {ESTreeNode[]} an array of converted ESTreeNode params
*/
function convertParameters(parameters: ts.NodeArray<ts.Node>): ESTreeNode[] {
if (!parameters || !parameters.length) {
return [];
}
return parameters.map(param => {
const convertedParam = convertChild(param) as ESTreeNode;
if (!param.decorators || !param.decorators.length) {
return convertedParam;
}
return Object.assign(convertedParam, {
decorators: param.decorators.map(convertChild)
});
});
}
/**
* For nodes that are copied directly from the TypeScript AST into
* ESTree mostly as-is. The only difference is the addition of a type
* property instead of a kind property. Recursively copies all children.
* @returns {void}
*/
function deeplyCopy(): void {
const customType = `TS${SyntaxKind[node.kind]}` as AST_NODE_TYPES;
/**
* If the "errorOnUnknownASTType" option is set to true, throw an error,
* otherwise fallback to just including the unknown type as-is.
*/
if (
additionalOptions.errorOnUnknownASTType &&
!AST_NODE_TYPES[customType]
) {
throw new Error(`Unknown AST_NODE_TYPE: "${customType}"`);
}
result.type = customType;
Object.keys(node)
.filter(
key =>
!/^(?:_children|kind|parent|pos|end|flags|modifierFlagsCache|jsDoc)$/.test(
key
)
)
.forEach(key => {
if (key === 'type') {
result.typeAnnotation = (node as any).type
? convertTypeAnnotation((node as any).type)
: null;
} else if (key === 'typeArguments') {
result.typeParameters = (node as any).typeArguments
? convertTypeArgumentsToTypeParameters((node as any).typeArguments)
: null;
} else if (key === 'typeParameters') {
result.typeParameters = (node as any).typeParameters
? convertTSTypeParametersToTypeParametersDeclaration(
(node as any).typeParameters
)
: null;
} else if (key === 'decorators') {
if (node.decorators && node.decorators.length) {
result.decorators = node.decorators.map(convertChild);
}
} else {
if (Array.isArray((node as any)[key])) {
(result as any)[key] = (node as any)[key].map(convertChild);
} else if (
(node as any)[key] &&
typeof (node as any)[key] === 'object' &&
(node as any)[key].kind
) {
// need to check node[key].kind to ensure we don't try to convert a symbol
(result as any)[key] = convertChild((node as any)[key]);
} else {
(result as any)[key] = (node as any)[key];
}
}
});
}
/**
* Converts a TypeScript JSX node.tagName into an ESTree node.name
* @param {ts.JsxTagNameExpression} tagName the tagName object from a JSX ts.Node
* @returns {Object} the converted ESTree name object
*/
function convertTypeScriptJSXTagNameToESTreeName(
tagName: ts.JsxTagNameExpression
): ESTreeNode {
const tagNameToken = convertToken(tagName, ast);
if (tagNameToken.type === AST_NODE_TYPES.JSXMemberExpression) {
const isNestedMemberExpression =
(node as any).tagName.expression.kind ===
SyntaxKind.PropertyAccessExpression;
// Convert TSNode left and right objects into ESTreeNode object
// and property objects
tagNameToken.object = convertChild((node as any).tagName.expression);
tagNameToken.property = convertChild((node as any).tagName.name);
// Assign the appropriate types
tagNameToken.object.type = isNestedMemberExpression
? AST_NODE_TYPES.JSXMemberExpression
: AST_NODE_TYPES.JSXIdentifier;
tagNameToken.property.type = AST_NODE_TYPES.JSXIdentifier;
if ((tagName as any).expression.kind === SyntaxKind.ThisKeyword) {
tagNameToken.object.name = 'this';
}
} else {
tagNameToken.type = AST_NODE_TYPES.JSXIdentifier;
tagNameToken.name = tagNameToken.value;
}
delete tagNameToken.value;
return tagNameToken;
}
/**
* Applies the given TS modifiers to the given result object.
* @param {ts.ModifiersArray} modifiers original ts.Nodes from the node.modifiers array
* @returns {void} (the current result object will be mutated)
*/
function applyModifiersToResult(modifiers?: ts.ModifiersArray): void {
if (!modifiers || !modifiers.length) {
return;
}
/**
* Some modifiers are explicitly handled by applying them as
* boolean values on the result node. As well as adding them
* to the result, we remove them from the array, so that they
* are not handled twice.
*/
const handledModifierIndices: { [key: number]: boolean } = {};
for (let i = 0; i < modifiers.length; i++) {
const modifier = modifiers[i];
switch (modifier.kind) {
/**
* Ignore ExportKeyword and DefaultKeyword, they are handled
* via the fixExports utility function
*/
case SyntaxKind.ExportKeyword:
case SyntaxKind.DefaultKeyword:
handledModifierIndices[i] = true;
break;
case SyntaxKind.ConstKeyword:
result.const = true;
handledModifierIndices[i] = true;
break;
case SyntaxKind.DeclareKeyword:
result.declare = true;
handledModifierIndices[i] = true;
break;
default:
}
}
/**
* If there are still valid modifiers available which have
* not been explicitly handled above, we just convert and
* add the modifiers array to the result node.
*/
const remainingModifiers = modifiers.filter(
(_, i) => !handledModifierIndices[i]
);
if (!remainingModifiers || !remainingModifiers.length) {
return;
}
result.modifiers = remainingModifiers.map(convertChild);
}
/**
* Uses the current TSNode's end location for its `type` to adjust the location data of the given
* ESTreeNode, which should be the parent of the final typeAnnotation node
* @param {ESTreeNode} typeAnnotationParent The node that will have its location data mutated
* @returns {void}
*/
function fixTypeAnnotationParentLocation(
typeAnnotationParent: ESTreeNode
): void {
typeAnnotationParent.range[1] = (node as any).type.getEnd();
typeAnnotationParent.loc = getLocFor(
typeAnnotationParent.range[0],
typeAnnotationParent.range[1],
ast
);
}
/**
* The core of the conversion logic:
* Identify and convert each relevant TypeScript SyntaxKind
*/
switch (node.kind) {
case SyntaxKind.SourceFile:
Object.assign(result, {
type: AST_NODE_TYPES.Program,
body: convertBodyExpressions(node.statements),
// externalModuleIndicator is internal field in TSC
sourceType: (node as any).externalModuleIndicator ? 'module' : 'script'
});
result.range[1] = node.endOfFileToken.end;
result.loc = getLocFor(node.getStart(ast), result.range[1], ast);
break;
case SyntaxKind.Block:
Object.assign(result, {
type: AST_NODE_TYPES.BlockStatement,
body: convertBodyExpressions(node.statements)
});
break;
case SyntaxKind.Identifier:
Object.assign(result, {
type: AST_NODE_TYPES.Identifier,
name: node.text
});
break;
case SyntaxKind.WithStatement:
Object.assign(result, {
type: AST_NODE_TYPES.WithStatement,
object: convertChild(node.expression),
body: convertChild(node.statement)
});
break;
// Control Flow
case SyntaxKind.ReturnStatement:
Object.assign(result, {
type: AST_NODE_TYPES.ReturnStatement,
argument: convertChild(node.expression)
});
break;
case SyntaxKind.LabeledStatement:
Object.assign(result, {
type: AST_NODE_TYPES.LabeledStatement,
label: convertChild(node.label),
body: convertChild(node.statement)
});
break;
case SyntaxKind.BreakStatement:
case SyntaxKind.ContinueStatement:
Object.assign(result, {
type: SyntaxKind[node.kind],
label: convertChild(node.label)
});
break;
// Choice
case SyntaxKind.IfStatement:
Object.assign(result, {
type: AST_NODE_TYPES.IfStatement,
test: convertChild(node.expression),
consequent: convertChild(node.thenStatement),
alternate: convertChild(node.elseStatement)
});
break;
case SyntaxKind.SwitchStatement:
Object.assign(result, {
type: AST_NODE_TYPES.SwitchStatement,
discriminant: convertChild(node.expression),
cases: node.caseBlock.clauses.map(convertChild)
});
break;
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
Object.assign(result, {
type: AST_NODE_TYPES.SwitchCase,
// expression is present in case only
test:
node.kind === SyntaxKind.CaseClause
? convertChild(node.expression)
: null,
consequent: node.statements.map(convertChild)
});
break;
// Exceptions
case SyntaxKind.ThrowStatement:
Object.assign(result, {
type: AST_NODE_TYPES.ThrowStatement,
argument: convertChild(node.expression)
});
break;
case SyntaxKind.TryStatement:
Object.assign(result, {
type: AST_NODE_TYPES.TryStatement,
block: convert({
node: node.tryBlock,
parent: null,
ast,
additionalOptions
}),
handler: convertChild(node.catchClause),
finalizer: convertChild(node.finallyBlock)
});
break;
case SyntaxKind.CatchClause:
Object.assign(result, {
type: AST_NODE_TYPES.CatchClause,
param: node.variableDeclaration
? convertChild(node.variableDeclaration.name)
: null,
body: convertChild(node.block)
});
break;
// Loops
case SyntaxKind.WhileStatement:
Object.assign(result, {
type: AST_NODE_TYPES.WhileStatement,
test: convertChild(node.expression),
body: convertChild(node.statement)
});
break;
/**
* Unlike other parsers, TypeScript calls a "DoWhileStatement"
* a "DoStatement"
*/
case SyntaxKind.DoStatement:
Object.assign(result, {
type: AST_NODE_TYPES.DoWhileStatement,
test: convertChild(node.expression),
body: convertChild(node.statement)
});
break;
case SyntaxKind.ForStatement:
Object.assign(result, {
type: AST_NODE_TYPES.ForStatement,
init: convertChild(node.initializer),
test: convertChild(node.condition),
update: convertChild(node.incrementor),
body: convertChild(node.statement)
});
break;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement: {
Object.assign(result, {
type: SyntaxKind[node.kind],
left: convertPattern(node.initializer),
right: convertChild(node.expression),
body: convertChild(node.statement)
});
// await is only available in for of statement
if (node.kind === SyntaxKind.ForOfStatement) {
(result as any).await = Boolean(
node.awaitModifier &&
node.awaitModifier.kind === SyntaxKind.AwaitKeyword
);
}
break;
}
// Declarations
case SyntaxKind.FunctionDeclaration: {
const isDeclare = hasModifier(SyntaxKind.DeclareKeyword, node);
let functionDeclarationType = AST_NODE_TYPES.FunctionDeclaration;
if (isDeclare || !node.body) {
functionDeclarationType = AST_NODE_TYPES.TSDeclareFunction;
}
Object.assign(result, {
type: functionDeclarationType,
id: convertChild(node.name),
generator: !!node.asteriskToken,
expression: false,
async: hasModifier(SyntaxKind.AsyncKeyword, node),
params: convertParameters(node.parameters),
body: convertChild(node.body) || undefined
});
// Process returnType
if (node.type) {
result.returnType = convertTypeAnnotation(node.type);
}
if (isDeclare) {
result.declare = true;
}
// Process typeParameters
if (node.typeParameters && node.typeParameters.length) {
result.typeParameters = convertTSTypeParametersToTypeParametersDeclaration(
node.typeParameters
);
}
// check for exports
result = fixExports(node, result, ast);
break;
}
case SyntaxKind.VariableDeclaration: {
Object.assign(result, {
type: AST_NODE_TYPES.VariableDeclarator,
id: convertPattern(node.name),
init: convertChild(node.initializer)
});
if (node.exclamationToken) {
(result as any).definite = true;
}
if (node.type) {
(result as any).id.typeAnnotation = convertTypeAnnotation(node.type);
fixTypeAnnotationParentLocation((result as any).id);
}
break;
}
case SyntaxKind.VariableStatement:
Object.assign(result, {
type: AST_NODE_TYPES.VariableDeclaration,
declarations: node.declarationList.declarations.map(convertChild),
kind: getDeclarationKind(node.declarationList)
});
if (hasModifier(SyntaxKind.DeclareKeyword, node)) {
result.declare = true;
}
// check for exports
result = fixExports(node, result, ast);
break;
// mostly for for-of, for-in
case SyntaxKind.VariableDeclarationList:
Object.assign(result, {
type: AST_NODE_TYPES.VariableDeclaration,
declarations: node.declarations.map(convertChild),
kind: getDeclarationKind(node)
});
break;
// Expressions
case SyntaxKind.ExpressionStatement:
Object.assign(result, {
type: AST_NODE_TYPES.ExpressionStatement,
expression: convertChild(node.expression)
});
break;
case SyntaxKind.ThisKeyword:
Object.assign(result, {
type: AST_NODE_TYPES.ThisExpression
});
break;
case SyntaxKind.ArrayLiteralExpression: {
// TypeScript uses ArrayLiteralExpression in destructuring assignment, too
if (config.allowPattern) {
Object.assign(result, {
type: AST_NODE_TYPES.ArrayPattern,
elements: node.elements.map(convertPattern)
});
} else {
Object.assign(result, {
type: AST_NODE_TYPES.ArrayExpression,
elements: node.elements.map(convertChild)
});
}
break;
}
case SyntaxKind.ObjectLiteralExpression: {
// TypeScript uses ObjectLiteralExpression in destructuring assignment, too
if (config.allowPattern) {
Object.assign(result, {
type: AST_NODE_TYPES.ObjectPattern,
properties: node.properties.map(convertPattern)
});
} else {
Object.assign(result, {
type: AST_NODE_TYPES.ObjectExpression,
properties: node.properties.map(convertChild)
});
}
break;
}
case SyntaxKind.PropertyAssignment:
Object.assign(result, {
type: AST_NODE_TYPES.Property,
key: convertChild(node.name),
value: converter(
node.initializer,
config.inTypeMode,
config.allowPattern
),
computed: isComputedProperty(node.name),
method: false,
shorthand: false,
kind: 'init'
});
break;
case SyntaxKind.ShorthandPropertyAssignment: {
if (node.objectAssignmentInitializer) {
Object.assign(result, {
type: AST_NODE_TYPES.Property,
key: convertChild(node.name),
value: {
type: AST_NODE_TYPES.AssignmentPattern,
left: convertPattern(node.name),
right: convertChild(node.objectAssignmentInitializer),
loc: result.loc,
range: result.range
},
computed: false,
method: false,
shorthand: true,
kind: 'init'
});
} else {
// TODO: this node has no initializer field
Object.assign(result, {
type: AST_NODE_TYPES.Property,
key: convertChild(node.name),
value: convertChild((node as any).initializer || node.name),
computed: false,
method: false,
shorthand: true,
kind: 'init'
});
}
break;
}
case SyntaxKind.ComputedPropertyName:
if (parent!.kind === SyntaxKind.ObjectLiteralExpression) {
// TODO: ComputedPropertyName has no name field
Object.assign(result, {
type: AST_NODE_TYPES.Property,
key: convertChild((node as any).name),
value: convertChild((node as any).name),
computed: false,
method: false,
shorthand: true,
kind: 'init'
});
} else {
return convertChild(node.expression);
}
break;
case SyntaxKind.PropertyDeclaration: {
const isAbstract = hasModifier(SyntaxKind.AbstractKeyword, node);
Object.assign(result, {
type: isAbstract
? AST_NODE_TYPES.TSAbstractClassProperty
: AST_NODE_TYPES.ClassProperty,
key: convertChild(node.name),
value: convertChild(node.initializer),
computed: isComputedProperty(node.name),
static: hasModifier(SyntaxKind.StaticKeyword, node),
readonly: hasModifier(SyntaxKind.ReadonlyKeyword, node) || undefined
});
if (node.type) {
result.typeAnnotation = convertTypeAnnotation(node.type);
}
if (node.decorators) {
result.decorators = node.decorators.map(convertChild);
}
const accessibility = getTSNodeAccessibility(node);
if (accessibility) {
result.accessibility = accessibility;
}
if (node.name.kind === SyntaxKind.Identifier && node.questionToken) {
result.optional = true;
}
if (node.exclamationToken) {
(result as any).definite = true;
}
if (
(result as any).key.type === AST_NODE_TYPES.Literal &&
node.questionToken
) {
result.optional = true;
}
break;
}
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration: {
const openingParen = findFirstMatchingToken(
node.name,
ast,
(token: any) => {
if (!token || !token.kind) {
return false;
}
return getTextForTokenKind(token.kind) === '(';
},
ast
);
const methodLoc = ast.getLineAndCharacterOfPosition(
(openingParen as any).getStart(ast)
),
nodeIsMethod = node.kind === SyntaxKind.MethodDeclaration,
method: ESTreeNode = {
type: AST_NODE_TYPES.FunctionExpression,
id: null,
generator: !!node.asteriskToken,
expression: false, // ESTreeNode as ESTreeNode here
async: hasModifier(SyntaxKind.AsyncKeyword, node),
body: convertChild(node.body),
range: [node.parameters.pos - 1, result.range[1]],
loc: {
start: {
line: methodLoc.line + 1,
column: methodLoc.character
},
end: result.loc.end
}
} as any;
if (node.type) {
(method as any).returnType = convertTypeAnnotation(node.type);
}
if (parent!.kind === SyntaxKind.ObjectLiteralExpression) {
(method as any).params = node.parameters.map(convertChild);
Object.assign(result, {
type: AST_NODE_TYPES.Property,
key: convertChild(node.name),
value: method,
computed: isComputedProperty(node.name),
method: nodeIsMethod,
shorthand: false,
kind: 'init'
});
} else {
// class
/**
* Unlike in object literal methods, class method params can have decorators
*/
(method as any).params = convertParameters(node.parameters);
/**
* TypeScript class methods can be defined as "abstract"
*/
const methodDefinitionType = hasModifier(
SyntaxKind.AbstractKeyword,
node
)
? AST_NODE_TYPES.TSAbstractMethodDefinition
: AST_NODE_TYPES.MethodDefinition;
Object.assign(result, {
type: methodDefinitionType,
key: convertChild(node.name),
value: method,
computed: isComputedProperty(node.name),
static: hasModifier(SyntaxKind.StaticKeyword, node),
kind: 'method'
});
if (node.decorators) {
result.decorators = node.decorators.map(convertChild);
}
const accessibility = getTSNodeAccessibility(node);
if (accessibility) {
result.accessibility = accessibility;
}
}
if (
(result as any).key.type === AST_NODE_TYPES.Identifier &&
node.questionToken
) {