-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
convert.ts
2528 lines (2258 loc) · 84.3 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,
findNextToken,
getBinaryExpressionType,
getDeclarationKind,
getLastModifier,
getLineAndCharacterFor,
getLocFor,
getRange,
getTextForTokenKind,
getTSNodeAccessibility,
hasModifier,
isComma,
isComputedProperty,
isESTreeClassMember,
isOptional,
unescapeStringLiteralText,
} from './node-utils';
import { AST_NODE_TYPES, TSESTree } from './ts-estree';
import { TSNode } from './ts-nodes';
const SyntaxKind = ts.SyntaxKind;
interface ConverterOptions {
errorOnUnknownASTType: boolean;
useJSXTextNode: boolean;
shouldProvideParserServices: boolean;
}
/**
* Extends and formats a given error object
* @param error the error object
* @returns converted error object
*/
export function convertError(error: any) {
return createError(
error.file,
error.start,
error.message || error.messageText,
);
}
export class Converter {
private readonly ast: ts.SourceFile;
private options: ConverterOptions;
private esTreeNodeToTSNodeMap = new WeakMap();
private tsNodeToESTreeNodeMap = new WeakMap();
private allowPattern: boolean = false;
private inTypeMode: boolean = false;
/**
* Converts a TypeScript node into an ESTree node
* @param ast the full TypeScript AST
* @param options additional options for the conversion
* @returns the converted ESTreeNode
*/
constructor(ast: ts.SourceFile, options: ConverterOptions) {
this.ast = ast;
this.options = options;
}
getASTMaps() {
return {
esTreeNodeToTSNodeMap: this.esTreeNodeToTSNodeMap,
tsNodeToESTreeNodeMap: this.tsNodeToESTreeNodeMap,
};
}
convertProgram(): TSESTree.Program {
return this.converter(this.ast) as TSESTree.Program;
}
/**
* Converts a TypeScript node into an ESTree node.
* @param node the child ts.Node
* @param parent parentNode
* @param inTypeMode flag to determine if we are in typeMode
* @param allowPattern flag to determine if patterns are allowed
* @returns the converted ESTree node
*/
private converter(
node?: ts.Node,
parent?: ts.Node,
inTypeMode?: boolean,
allowPattern?: boolean,
): any {
/**
* Exit early for null and undefined
*/
if (!node) {
return null;
}
const typeMode = this.inTypeMode;
const pattern = this.allowPattern;
if (inTypeMode !== undefined) {
this.inTypeMode = inTypeMode;
}
if (allowPattern !== undefined) {
this.allowPattern = allowPattern;
}
let result = this.convertNode(node as TSNode, parent || node.parent);
this.registerTSNodeInNodeMap(node, result);
this.inTypeMode = typeMode;
this.allowPattern = pattern;
return result;
}
/**
* Fixes the exports of the given ts.Node
* @param node the ts.Node
* @param result result
* @returns the ESTreeNode with fixed exports
*/
private fixExports<T extends TSESTree.ExportDeclaration>(
node: ts.Node,
result: T,
): TSESTree.ExportDefaultDeclaration | TSESTree.ExportNamedDeclaration | T {
// check for exports
if (node.modifiers && node.modifiers[0].kind === SyntaxKind.ExportKeyword) {
/**
* Make sure that original node is registered instead of export
*/
this.registerTSNodeInNodeMap(node, result);
const exportKeyword = node.modifiers[0];
const nextModifier = node.modifiers[1];
const declarationIsDefault =
nextModifier && nextModifier.kind === SyntaxKind.DefaultKeyword;
const varToken = declarationIsDefault
? findNextToken(nextModifier, this.ast, this.ast)
: findNextToken(exportKeyword, this.ast, this.ast);
result.range[0] = varToken!.getStart(this.ast);
result.loc = getLocFor(result.range[0], result.range[1], this.ast);
if (declarationIsDefault) {
return this.createNode<TSESTree.ExportDefaultDeclaration>(node, {
type: AST_NODE_TYPES.ExportDefaultDeclaration,
declaration: result,
range: [exportKeyword.getStart(this.ast), result.range[1]],
});
} else {
return this.createNode<TSESTree.ExportNamedDeclaration>(node, {
type: AST_NODE_TYPES.ExportNamedDeclaration,
declaration: result,
specifiers: [],
source: null,
range: [exportKeyword.getStart(this.ast), result.range[1]],
});
}
}
return result;
}
/**
* Register specific TypeScript node into map with first ESTree node provided
*/
private registerTSNodeInNodeMap(
node: ts.Node,
result: TSESTree.BaseNode | null,
) {
if (result && this.options.shouldProvideParserServices) {
if (!this.tsNodeToESTreeNodeMap.has(node)) {
this.tsNodeToESTreeNodeMap.set(node, result);
}
}
}
/**
* Converts a TypeScript node into an ESTree node.
* @param child the child ts.Node
* @param parent parentNode
* @returns the converted ESTree node
*/
private convertPattern(child?: ts.Node, parent?: ts.Node): any | null {
return this.converter(child, parent, this.inTypeMode, true);
}
/**
* Converts a TypeScript node into an ESTree node.
* @param child the child ts.Node
* @param parent parentNode
* @returns the converted ESTree node
*/
private convertChild(child?: ts.Node, parent?: ts.Node): any | null {
return this.converter(child, parent, this.inTypeMode, false);
}
/**
* Converts a TypeScript node into an ESTree node.
* @param child the child ts.Node
* @param parent parentNode
* @returns the converted ESTree node
*/
private convertType(child?: ts.Node, parent?: ts.Node): any | null {
return this.converter(child, parent, true, false);
}
private createNode<T extends TSESTree.BaseNode = TSESTree.BaseNode>(
node: ts.Node,
data: TSESTree.OptionalRangeAndLoc<T>,
): T {
const result = data;
if (!result.range) {
result.range = getRange(node, this.ast);
}
if (!result.loc) {
result.loc = getLocFor(result.range[0], result.range[1], this.ast);
}
if (result && this.options.shouldProvideParserServices) {
this.esTreeNodeToTSNodeMap.set(result, node);
}
return result as T;
}
/**
* Converts a child into a type annotation. This creates an intermediary
* TypeAnnotation node to match what Flow does.
* @param child The TypeScript AST node to convert.
* @param parent parentNode
* @returns The type annotation node.
*/
private convertTypeAnnotation(
child: ts.TypeNode,
parent: ts.Node,
): TSESTree.TSTypeAnnotation {
// in FunctionType and ConstructorType typeAnnotation has 2 characters `=>` and in other places is just colon
const offset =
parent.kind === SyntaxKind.FunctionType ||
parent.kind === SyntaxKind.ConstructorType
? 2
: 1;
const annotationStartCol = child.getFullStart() - offset;
const loc = getLocFor(annotationStartCol, child.end, this.ast);
return {
type: AST_NODE_TYPES.TSTypeAnnotation,
loc,
range: [annotationStartCol, child.end],
typeAnnotation: this.convertType(child),
};
}
/**
* Coverts body Nodes and add directive field to StringLiterals
* @param nodes of ts.Node
* @param parent parentNode
* @returns Array of body statements
*/
private convertBodyExpressions(
nodes: ts.NodeArray<ts.Statement>,
parent: ts.SourceFile | ts.Block | ts.ModuleBlock,
): any[] {
let allowDirectives = canContainDirective(parent);
return (
nodes
.map(statement => {
const child = this.convertChild(statement);
if (allowDirectives) {
if (
child &&
child.expression &&
ts.isExpressionStatement(statement) &&
ts.isStringLiteral(statement.expression)
) {
const raw = child.expression.raw;
child.directive = raw.slice(1, -1);
return child; // child can be null but it's filtered below
} else {
allowDirectives = false;
}
}
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 to TSTypeParameterInstantiation node
* @param typeArguments ts.Node typeArguments
* @returns TypeParameterInstantiation node
*/
private convertTypeArgumentsToTypeParameters(
typeArguments: ts.NodeArray<ts.TypeNode>,
): TSESTree.TSTypeParameterInstantiation {
const greaterThanToken = findNextToken(typeArguments, this.ast, this.ast)!;
return {
type: AST_NODE_TYPES.TSTypeParameterInstantiation,
range: [typeArguments.pos - 1, greaterThanToken.end],
loc: getLocFor(typeArguments.pos - 1, greaterThanToken.end, this.ast),
params: typeArguments.map(typeArgument => this.convertType(typeArgument)),
};
}
/**
* Converts a ts.Node's typeParameters to TSTypeParameterDeclaration node
* @param typeParameters ts.Node typeParameters
* @returns TypeParameterDeclaration node
*/
private convertTSTypeParametersToTypeParametersDeclaration(
typeParameters: ts.NodeArray<ts.TypeParameterDeclaration>,
): TSESTree.TSTypeParameterDeclaration {
const greaterThanToken = findNextToken(typeParameters, this.ast, this.ast)!;
return {
type: AST_NODE_TYPES.TSTypeParameterDeclaration,
range: [typeParameters.pos - 1, greaterThanToken.end],
loc: getLocFor(typeParameters.pos - 1, greaterThanToken.end, this.ast),
params: typeParameters.map(typeParameter =>
this.convertType(typeParameter),
),
};
}
/**
* Converts an array of ts.Node parameters into an array of ESTreeNode params
* @param parameters An array of ts.Node params to be converted
* @returns an array of converted ESTreeNode params
*/
private convertParameters(
parameters: ts.NodeArray<ts.ParameterDeclaration>,
): TSESTree.Parameter[] {
if (!parameters || !parameters.length) {
return [];
}
return parameters.map(param => {
const convertedParam = this.convertChild(param) as TSESTree.Parameter;
if (param.decorators && param.decorators.length) {
convertedParam.decorators = param.decorators.map(el =>
this.convertChild(el),
);
}
return convertedParam;
});
}
/**
* 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.
*/
private deeplyCopy(node: ts.Node): any {
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 (this.options.errorOnUnknownASTType && !AST_NODE_TYPES[customType]) {
throw new Error(`Unknown AST_NODE_TYPE: "${customType}"`);
}
const result = this.createNode<any>(node, {
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
? this.convertTypeAnnotation((node as any).type, node)
: null;
} else if (key === 'typeArguments') {
result.typeParameters = (node as any).typeArguments
? this.convertTypeArgumentsToTypeParameters(
(node as any).typeArguments,
)
: null;
} else if (key === 'typeParameters') {
result.typeParameters = (node as any).typeParameters
? this.convertTSTypeParametersToTypeParametersDeclaration(
(node as any).typeParameters,
)
: null;
} else if (key === 'decorators') {
if (node.decorators && node.decorators.length) {
result.decorators = node.decorators.map((el: any) =>
this.convertChild(el),
);
}
} else {
if (Array.isArray((node as any)[key])) {
result[key] = (node as any)[key].map((el: any) =>
this.convertChild(el),
);
} 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[key] = this.convertChild((node as any)[key]);
} else {
result[key] = (node as any)[key];
}
}
});
return result;
}
/**
* Converts a TypeScript JSX node.tagName into an ESTree node.name
* @param node the tagName object from a JSX ts.Node
* @param parent
* @returns the converted ESTree name object
*/
private convertJSXTagName(
node: ts.JsxTagNameExpression,
parent: ts.Node,
): TSESTree.JSXMemberExpression | TSESTree.JSXIdentifier {
let result: TSESTree.JSXMemberExpression | TSESTree.JSXIdentifier;
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
result = this.createNode<TSESTree.JSXMemberExpression>(node, {
type: AST_NODE_TYPES.JSXMemberExpression,
object: this.convertJSXTagName(node.expression, parent),
property: this.convertJSXTagName(
node.name,
parent,
) as TSESTree.JSXIdentifier,
});
break;
case SyntaxKind.ThisKeyword:
result = this.createNode<TSESTree.JSXIdentifier>(node, {
type: AST_NODE_TYPES.JSXIdentifier,
name: 'this',
});
break;
case SyntaxKind.Identifier:
default:
result = this.createNode<TSESTree.JSXIdentifier>(node, {
type: AST_NODE_TYPES.JSXIdentifier,
name: node.text,
});
break;
}
this.registerTSNodeInNodeMap(node, result);
return result;
}
/**
* Applies the given TS modifiers to the given result object.
* @param result
* @param modifiers original ts.Nodes from the node.modifiers array
* @returns the current result object will be mutated
* @deprecated This method adds not standardized `modifiers` property in nodes
*/
private applyModifiersToResult(
result: TSESTree.TSEnumDeclaration | TSESTree.TSModuleDeclaration,
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 as any).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(el => this.convertChild(el));
}
/**
* Uses the provided range location to adjust the location data of the given Node
* @param result The node that will have its location data mutated
* @param childRange The child node range used to expand location
*/
private fixParentLocation(
result: TSESTree.BaseNode,
childRange: [number, number],
): void {
if (childRange[0] < result.range[0]) {
result.range[0] = childRange[0];
result.loc.start = getLineAndCharacterFor(result.range[0], this.ast);
}
if (childRange[1] > result.range[1]) {
result.range[1] = childRange[1];
result.loc.end = getLineAndCharacterFor(result.range[1], this.ast);
}
}
/**
* Converts a TypeScript node into an ESTree node.
* The core of the conversion logic:
* Identify and convert each relevant TypeScript SyntaxKind
* @param node the child ts.Node
* @param parent parentNode
* @returns the converted ESTree node
*/
private convertNode(node: TSNode, parent: ts.Node): TSESTree.Node | null {
switch (node.kind) {
case SyntaxKind.SourceFile: {
return this.createNode<TSESTree.Program>(node, {
type: AST_NODE_TYPES.Program,
body: this.convertBodyExpressions(node.statements, node),
// externalModuleIndicator is internal field in TSC
sourceType: (node as any).externalModuleIndicator
? 'module'
: 'script',
range: [node.getStart(this.ast), node.endOfFileToken.end],
});
}
case SyntaxKind.Block: {
return this.createNode<TSESTree.BlockStatement>(node, {
type: AST_NODE_TYPES.BlockStatement,
body: this.convertBodyExpressions(node.statements, node),
});
}
case SyntaxKind.Identifier: {
return this.createNode<TSESTree.Identifier>(node, {
type: AST_NODE_TYPES.Identifier,
name: node.text,
});
}
case SyntaxKind.WithStatement:
return this.createNode<TSESTree.WithStatement>(node, {
type: AST_NODE_TYPES.WithStatement,
object: this.convertChild(node.expression),
body: this.convertChild(node.statement),
});
// Control Flow
case SyntaxKind.ReturnStatement:
return this.createNode<TSESTree.ReturnStatement>(node, {
type: AST_NODE_TYPES.ReturnStatement,
argument: this.convertChild(node.expression),
});
case SyntaxKind.LabeledStatement:
return this.createNode<TSESTree.LabeledStatement>(node, {
type: AST_NODE_TYPES.LabeledStatement,
label: this.convertChild(node.label),
body: this.convertChild(node.statement),
});
case SyntaxKind.ContinueStatement:
return this.createNode<TSESTree.ContinueStatement>(node, {
type: AST_NODE_TYPES.ContinueStatement,
label: this.convertChild(node.label),
});
case SyntaxKind.BreakStatement:
return this.createNode<TSESTree.BreakStatement>(node, {
type: AST_NODE_TYPES.BreakStatement,
label: this.convertChild(node.label),
});
// Choice
case SyntaxKind.IfStatement:
return this.createNode<TSESTree.IfStatement>(node, {
type: AST_NODE_TYPES.IfStatement,
test: this.convertChild(node.expression),
consequent: this.convertChild(node.thenStatement),
alternate: this.convertChild(node.elseStatement),
});
case SyntaxKind.SwitchStatement:
return this.createNode<TSESTree.SwitchStatement>(node, {
type: AST_NODE_TYPES.SwitchStatement,
discriminant: this.convertChild(node.expression),
cases: node.caseBlock.clauses.map(el => this.convertChild(el)),
});
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
return this.createNode<TSESTree.SwitchCase>(node, {
type: AST_NODE_TYPES.SwitchCase,
// expression is present in case only
test:
node.kind === SyntaxKind.CaseClause
? this.convertChild(node.expression)
: null,
consequent: node.statements.map(el => this.convertChild(el)),
});
// Exceptions
case SyntaxKind.ThrowStatement:
return this.createNode<TSESTree.ThrowStatement>(node, {
type: AST_NODE_TYPES.ThrowStatement,
argument: this.convertChild(node.expression),
});
case SyntaxKind.TryStatement:
return this.createNode<TSESTree.TryStatement>(node, {
type: AST_NODE_TYPES.TryStatement,
block: this.convertChild(node.tryBlock),
handler: this.convertChild(node.catchClause),
finalizer: this.convertChild(node.finallyBlock),
});
case SyntaxKind.CatchClause:
return this.createNode<TSESTree.CatchClause>(node, {
type: AST_NODE_TYPES.CatchClause,
param: node.variableDeclaration
? this.convertChild(node.variableDeclaration.name)
: null,
body: this.convertChild(node.block),
});
// Loops
case SyntaxKind.WhileStatement:
return this.createNode<TSESTree.WhileStatement>(node, {
type: AST_NODE_TYPES.WhileStatement,
test: this.convertChild(node.expression),
body: this.convertChild(node.statement),
});
/**
* Unlike other parsers, TypeScript calls a "DoWhileStatement"
* a "DoStatement"
*/
case SyntaxKind.DoStatement:
return this.createNode<TSESTree.DoWhileStatement>(node, {
type: AST_NODE_TYPES.DoWhileStatement,
test: this.convertChild(node.expression),
body: this.convertChild(node.statement),
});
case SyntaxKind.ForStatement:
return this.createNode<TSESTree.ForStatement>(node, {
type: AST_NODE_TYPES.ForStatement,
init: this.convertChild(node.initializer),
test: this.convertChild(node.condition),
update: this.convertChild(node.incrementor),
body: this.convertChild(node.statement),
});
case SyntaxKind.ForInStatement:
return this.createNode<TSESTree.ForInStatement>(node, {
type: AST_NODE_TYPES.ForInStatement,
left: this.convertPattern(node.initializer),
right: this.convertChild(node.expression),
body: this.convertChild(node.statement),
});
case SyntaxKind.ForOfStatement:
return this.createNode<TSESTree.ForOfStatement>(node, {
type: AST_NODE_TYPES.ForOfStatement,
left: this.convertPattern(node.initializer),
right: this.convertChild(node.expression),
body: this.convertChild(node.statement),
await: Boolean(
node.awaitModifier &&
node.awaitModifier.kind === SyntaxKind.AwaitKeyword,
),
});
// Declarations
case SyntaxKind.FunctionDeclaration: {
const isDeclare = hasModifier(SyntaxKind.DeclareKeyword, node);
const result = this.createNode<
TSESTree.TSDeclareFunction | TSESTree.FunctionDeclaration
>(node, {
type:
isDeclare || !node.body
? AST_NODE_TYPES.TSDeclareFunction
: AST_NODE_TYPES.FunctionDeclaration,
id: this.convertChild(node.name),
generator: !!node.asteriskToken,
expression: false,
async: hasModifier(SyntaxKind.AsyncKeyword, node),
params: this.convertParameters(node.parameters),
body: this.convertChild(node.body) || undefined,
});
// Process returnType
if (node.type) {
result.returnType = this.convertTypeAnnotation(node.type, node);
}
if (isDeclare) {
result.declare = true;
}
// Process typeParameters
if (node.typeParameters) {
result.typeParameters = this.convertTSTypeParametersToTypeParametersDeclaration(
node.typeParameters,
);
}
/**
* Semantically, decorators are not allowed on function declarations,
* but the TypeScript compiler will parse them and produce a valid AST,
* so we handle them here too.
*/
if (node.decorators) {
(result as any).decorators = node.decorators.map(el =>
this.convertChild(el),
);
}
// check for exports
return this.fixExports(node, result);
}
case SyntaxKind.VariableDeclaration: {
const result = this.createNode<TSESTree.VariableDeclarator>(node, {
type: AST_NODE_TYPES.VariableDeclarator,
id: this.convertPattern(node.name),
init: this.convertChild(node.initializer),
});
if (node.exclamationToken) {
result.definite = true;
}
if (node.type) {
result.id.typeAnnotation = this.convertTypeAnnotation(
node.type,
node,
);
this.fixParentLocation(result.id, result.id.typeAnnotation.range);
}
return result;
}
case SyntaxKind.VariableStatement: {
const result = this.createNode<TSESTree.VariableDeclaration>(node, {
type: AST_NODE_TYPES.VariableDeclaration,
declarations: node.declarationList.declarations.map(el =>
this.convertChild(el),
),
kind: getDeclarationKind(node.declarationList),
});
/**
* Semantically, decorators are not allowed on variable declarations,
* but the TypeScript compiler will parse them and produce a valid AST,
* so we handle them here too.
*/
if (node.decorators) {
(result as any).decorators = node.decorators.map(el =>
this.convertChild(el),
);
}
if (hasModifier(SyntaxKind.DeclareKeyword, node)) {
result.declare = true;
}
// check for exports
return this.fixExports(node, result);
}
// mostly for for-of, for-in
case SyntaxKind.VariableDeclarationList:
return this.createNode<TSESTree.VariableDeclaration>(node, {
type: AST_NODE_TYPES.VariableDeclaration,
declarations: node.declarations.map(el => this.convertChild(el)),
kind: getDeclarationKind(node),
});
// Expressions
case SyntaxKind.ExpressionStatement:
return this.createNode<TSESTree.ExpressionStatement>(node, {
type: AST_NODE_TYPES.ExpressionStatement,
expression: this.convertChild(node.expression),
});
case SyntaxKind.ThisKeyword:
return this.createNode<TSESTree.ThisExpression>(node, {
type: AST_NODE_TYPES.ThisExpression,
});
case SyntaxKind.ArrayLiteralExpression: {
// TypeScript uses ArrayLiteralExpression in destructuring assignment, too
if (this.allowPattern) {
return this.createNode<TSESTree.ArrayPattern>(node, {
type: AST_NODE_TYPES.ArrayPattern,
elements: node.elements.map(el => this.convertPattern(el)),
});
} else {
return this.createNode<TSESTree.ArrayExpression>(node, {
type: AST_NODE_TYPES.ArrayExpression,
elements: node.elements.map(el => this.convertChild(el)),
});
}
}
case SyntaxKind.ObjectLiteralExpression: {
// TypeScript uses ObjectLiteralExpression in destructuring assignment, too
if (this.allowPattern) {
return this.createNode<TSESTree.ObjectPattern>(node, {
type: AST_NODE_TYPES.ObjectPattern,
properties: node.properties.map(el => this.convertPattern(el)),
});
} else {
return this.createNode<TSESTree.ObjectExpression>(node, {
type: AST_NODE_TYPES.ObjectExpression,
properties: node.properties.map(el => this.convertChild(el)),
});
}
}
case SyntaxKind.PropertyAssignment:
return this.createNode<TSESTree.Property>(node, {
type: AST_NODE_TYPES.Property,
key: this.convertChild(node.name),
value: this.converter(
node.initializer,
node,
this.inTypeMode,
this.allowPattern,
),
computed: isComputedProperty(node.name),
method: false,
shorthand: false,
kind: 'init',
});
case SyntaxKind.ShorthandPropertyAssignment: {
if (node.objectAssignmentInitializer) {
return this.createNode<TSESTree.Property>(node, {
type: AST_NODE_TYPES.Property,
key: this.convertChild(node.name),
value: this.createNode<TSESTree.AssignmentPattern>(node, {
type: AST_NODE_TYPES.AssignmentPattern,
left: this.convertPattern(node.name),
right: this.convertChild(node.objectAssignmentInitializer),
}),
computed: false,
method: false,
shorthand: true,
kind: 'init',
});
} else {
return this.createNode<TSESTree.Property>(node, {
type: AST_NODE_TYPES.Property,
key: this.convertChild(node.name),
value: this.convertChild(node.name),
computed: false,
method: false,
shorthand: true,
kind: 'init',
});
}
}
case SyntaxKind.ComputedPropertyName:
return this.convertChild(node.expression);
case SyntaxKind.PropertyDeclaration: {
const isAbstract = hasModifier(SyntaxKind.AbstractKeyword, node);
const result = this.createNode<
TSESTree.TSAbstractClassProperty | TSESTree.ClassProperty
>(node, {
type: isAbstract
? AST_NODE_TYPES.TSAbstractClassProperty
: AST_NODE_TYPES.ClassProperty,
key: this.convertChild(node.name),
value: this.convertChild(node.initializer),
computed: isComputedProperty(node.name),
static: hasModifier(SyntaxKind.StaticKeyword, node),
readonly: hasModifier(SyntaxKind.ReadonlyKeyword, node) || undefined,
});
if (node.type) {
result.typeAnnotation = this.convertTypeAnnotation(node.type, node);
}
if (node.decorators) {
result.decorators = node.decorators.map(el => this.convertChild(el));
}
const accessibility = getTSNodeAccessibility(node);
if (accessibility) {
result.accessibility = accessibility;
}
if (node.name.kind === SyntaxKind.Identifier && node.questionToken) {
result.optional = true;
}
if (node.exclamationToken) {
result.definite = true;
}
if (result.key.type === AST_NODE_TYPES.Literal && node.questionToken) {
result.optional = true;
}
return result;
}
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.MethodDeclaration: {
const method = this.createNode<TSESTree.FunctionExpression>(node, {
type: AST_NODE_TYPES.FunctionExpression,
id: null,
generator: !!node.asteriskToken,
expression: false, // ESTreeNode as ESTreeNode here
async: hasModifier(SyntaxKind.AsyncKeyword, node),
body: this.convertChild(node.body),
range: [node.parameters.pos - 1, node.end],
params: [],
});
if (node.type) {
method.returnType = this.convertTypeAnnotation(node.type, node);
}
// Process typeParameters
if (node.typeParameters) {
method.typeParameters = this.convertTSTypeParametersToTypeParametersDeclaration(
node.typeParameters,
);
this.fixParentLocation(method, method.typeParameters.range);
}
let result:
| TSESTree.Property
| TSESTree.TSAbstractMethodDefinition
| TSESTree.MethodDefinition;
if (parent.kind === SyntaxKind.ObjectLiteralExpression) {
method.params = node.parameters.map(el => this.convertChild(el));
result = this.createNode<TSESTree.Property>(node, {
type: AST_NODE_TYPES.Property,
key: this.convertChild(node.name),
value: method,
computed: isComputedProperty(node.name),
method: node.kind === SyntaxKind.MethodDeclaration,
shorthand: false,
kind: 'init',
});
} else {