forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.ts
2909 lines (2592 loc) · 96.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
// There's lots of funny stuff due to the typing of ts.Node
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access */
import * as ts from 'typescript';
import { getDecorators, getModifiers } from './getModifiers';
import type { TSError } from './node-utils';
import {
canContainDirective,
createError,
findNextToken,
getBinaryExpressionType,
getDeclarationKind,
getLastModifier,
getLineAndCharacterFor,
getLocFor,
getRange,
getTextForTokenKind,
getTSNodeAccessibility,
hasModifier,
isChainExpression,
isChildUnwrappableOptionalChain,
isComma,
isComputedProperty,
isESTreeClassMember,
isOptional,
isThisInTypeQuery,
unescapeStringLiteralText,
} from './node-utils';
import type {
ParserWeakMap,
ParserWeakMapESTreeToTSNode,
} from './parser-options';
import type { SemanticOrSyntacticError } from './semantic-or-syntactic-errors';
import type { TSESTree, TSESTreeToTSNode, TSNode } from './ts-estree';
import { AST_NODE_TYPES } from './ts-estree';
const SyntaxKind = ts.SyntaxKind;
interface ConverterOptions {
errorOnUnknownASTType: boolean;
shouldPreserveNodeMaps: boolean;
}
/**
* Extends and formats a given error object
* @param error the error object
* @returns converted error object
*/
export function convertError(
error: ts.DiagnosticWithLocation | SemanticOrSyntacticError,
): TSError {
return createError(
error.file!,
error.start!,
('message' in error && error.message) || (error.messageText as string),
);
}
export interface ASTMaps {
esTreeNodeToTSNodeMap: ParserWeakMapESTreeToTSNode;
tsNodeToESTreeNodeMap: ParserWeakMap<TSNode, TSESTree.Node>;
}
export class Converter {
private readonly ast: ts.SourceFile;
private readonly options: ConverterOptions;
private readonly esTreeNodeToTSNodeMap = new WeakMap();
private readonly tsNodeToESTreeNodeMap = new WeakMap();
private allowPattern = 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(): ASTMaps {
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 allowPattern flag to determine if patterns are allowed
* @returns the converted ESTree node
*/
private converter(
node?: ts.Node,
parent?: ts.Node,
allowPattern?: boolean,
): any {
/**
* Exit early for null and undefined
*/
if (!node) {
return null;
}
const pattern = this.allowPattern;
if (allowPattern !== undefined) {
this.allowPattern = allowPattern;
}
const result = this.convertNode(
node as TSNode,
(parent ?? node.parent) as TSNode,
);
this.registerTSNodeInNodeMap(node, result);
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.DefaultExportDeclarations
| TSESTree.NamedExportDeclarations,
>(
node:
| ts.FunctionDeclaration
| ts.VariableStatement
| ts.ClassDeclaration
| ts.ClassExpression
| ts.TypeAliasDeclaration
| ts.ImportEqualsDeclaration
| ts.InterfaceDeclaration
| ts.EnumDeclaration
| ts.ModuleDeclaration,
result: T,
): TSESTree.ExportDefaultDeclaration | TSESTree.ExportNamedDeclaration | T {
// check for exports
const modifiers = getModifiers(node);
if (modifiers?.[0].kind === SyntaxKind.ExportKeyword) {
/**
* Make sure that original node is registered instead of export
*/
this.registerTSNodeInNodeMap(node, result);
const exportKeyword = modifiers[0];
const nextModifier = modifiers[1];
const declarationIsDefault =
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 as Exclude<typeof node, ts.ImportEqualsDeclaration>,
{
type: AST_NODE_TYPES.ExportDefaultDeclaration,
declaration: result as TSESTree.DefaultExportDeclarations,
range: [exportKeyword.getStart(this.ast), result.range[1]],
exportKind: 'value',
},
);
} else {
const isType =
result.type === AST_NODE_TYPES.TSInterfaceDeclaration ||
result.type === AST_NODE_TYPES.TSTypeAliasDeclaration;
const isDeclare = 'declare' in result && result.declare === true;
return this.createNode<TSESTree.ExportNamedDeclaration>(node, {
type: AST_NODE_TYPES.ExportNamedDeclaration,
// @ts-expect-error - TODO, narrow the types here
declaration: result,
specifiers: [],
source: null,
exportKind: isType || isDeclare ? 'type' : 'value',
range: [exportKeyword.getStart(this.ast), result.range[1]],
assertions: [],
});
}
}
return result;
}
/**
* Register specific TypeScript node into map with first ESTree node provided
*/
private registerTSNodeInNodeMap(
node: ts.Node,
result: TSESTree.Node | null,
): void {
if (result && this.options.shouldPreserveNodeMaps) {
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, 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, false);
}
private createNode<T extends TSESTree.Node = TSESTree.Node>(
// The 'parent' property will be added later if specified
node: Omit<TSESTreeToTSNode<T>, 'parent'>,
data: Omit<TSESTree.OptionalRangeAndLoc<T>, 'parent'>,
): 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.shouldPreserveNodeMaps) {
this.esTreeNodeToTSNodeMap.set(result, node);
}
return result as T;
}
private convertBindingNameWithTypeAnnotation(
name: ts.BindingName,
tsType: ts.TypeNode | undefined,
parent?: ts.Node,
): TSESTree.BindingName {
const id = this.convertPattern(name) as TSESTree.BindingName;
if (tsType) {
id.typeAnnotation = this.convertTypeAnnotation(tsType, parent);
this.fixParentLocation(id, id.typeAnnotation.range);
}
return id;
}
/**
* 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 | undefined,
): 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.convertChild(child),
} as TSESTree.TSTypeAnnotation;
}
/**
* Coverts body Nodes and add a 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
| ts.ClassStaticBlockDeclaration,
): TSESTree.Statement[] {
let allowDirectives = canContainDirective(parent);
return (
nodes
.map(statement => {
const child = this.convertChild(statement);
if (allowDirectives) {
if (
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.NodeArray typeArguments
* @param node parent used to create this node
* @returns TypeParameterInstantiation node
*/
private convertTypeArgumentsToTypeParameters(
typeArguments: ts.NodeArray<ts.TypeNode>,
node: TSESTreeToTSNode<TSESTree.TSTypeParameterInstantiation>,
): TSESTree.TSTypeParameterInstantiation {
const greaterThanToken = findNextToken(typeArguments, this.ast, this.ast)!;
return this.createNode<TSESTree.TSTypeParameterInstantiation>(node, {
type: AST_NODE_TYPES.TSTypeParameterInstantiation,
range: [typeArguments.pos - 1, greaterThanToken.end],
params: typeArguments.map(typeArgument =>
this.convertChild(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.convertChild(typeParameter),
),
} as TSESTree.TSTypeParameterDeclaration;
}
/**
* 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?.length) {
return [];
}
return parameters.map(param => {
const convertedParam = this.convertChild(param) as TSESTree.Parameter;
const decorators = getDecorators(param);
if (decorators?.length) {
convertedParam.decorators = decorators.map(el => this.convertChild(el));
}
return convertedParam;
});
}
private convertChainExpression(
node: TSESTree.ChainElement,
tsNode:
| ts.PropertyAccessExpression
| ts.ElementAccessExpression
| ts.CallExpression
| ts.NonNullExpression,
): TSESTree.ChainExpression | TSESTree.ChainElement {
const { child, isOptional } = ((): {
child: TSESTree.Node;
isOptional: boolean;
} => {
if (node.type === AST_NODE_TYPES.MemberExpression) {
return { child: node.object, isOptional: node.optional };
}
if (node.type === AST_NODE_TYPES.CallExpression) {
return { child: node.callee, isOptional: node.optional };
}
return { child: node.expression, isOptional: false };
})();
const isChildUnwrappable = isChildUnwrappableOptionalChain(tsNode, child);
if (!isChildUnwrappable && !isOptional) {
return node;
}
if (isChildUnwrappable && isChainExpression(child)) {
// unwrap the chain expression child
const newChild = child.expression;
if (node.type === AST_NODE_TYPES.MemberExpression) {
node.object = newChild;
} else if (node.type === AST_NODE_TYPES.CallExpression) {
node.callee = newChild;
} else {
node.expression = newChild;
}
}
return this.createNode<TSESTree.ChainExpression>(tsNode, {
type: AST_NODE_TYPES.ChainExpression,
expression: node,
});
}
/**
* 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: TSNode): any {
if (node.kind === ts.SyntaxKind.JSDocFunctionType) {
throw createError(
this.ast,
node.pos,
'JSDoc types can only be used inside documentation comments.',
);
}
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,
});
if ('type' in node) {
result.typeAnnotation =
node.type && 'kind' in node.type && ts.isTypeNode(node.type)
? this.convertTypeAnnotation(node.type, node)
: null;
}
if ('typeArguments' in node) {
result.typeParameters =
node.typeArguments && 'pos' in node.typeArguments
? this.convertTypeArgumentsToTypeParameters(node.typeArguments, node)
: null;
}
if ('typeParameters' in node) {
result.typeParameters =
node.typeParameters && 'pos' in node.typeParameters
? this.convertTSTypeParametersToTypeParametersDeclaration(
node.typeParameters,
)
: null;
}
const decorators = getDecorators(node);
if (decorators?.length) {
result.decorators = decorators.map(el => this.convertChild(el));
}
// keys we never want to clone from the base typescript node as they
// introduce garbage into our AST
const KEYS_TO_NOT_COPY = new Set([
'_children',
'decorators',
'end',
'flags',
'illegalDecorators',
'heritageClauses',
'locals',
'localSymbol',
'jsDoc',
'kind',
'modifierFlagsCache',
'modifiers',
'nextContainer',
'parent',
'pos',
'symbol',
'transformFlags',
'type',
'typeArguments',
'typeParameters',
]);
Object.entries<any>(node)
.filter(([key]) => !KEYS_TO_NOT_COPY.has(key))
.forEach(([key, value]) => {
if (Array.isArray(value)) {
result[key] = value.map(el => this.convertChild(el as TSNode));
} else if (value && typeof value === 'object' && value.kind) {
// need to check node[key].kind to ensure we don't try to convert a symbol
result[key] = this.convertChild(value as TSNode);
} else {
result[key] = value;
}
});
return result;
}
private convertJSXIdentifier(
node: ts.Identifier | ts.ThisExpression,
): TSESTree.JSXIdentifier {
const result = this.createNode<TSESTree.JSXIdentifier>(node, {
type: AST_NODE_TYPES.JSXIdentifier,
name: node.getText(),
});
this.registerTSNodeInNodeMap(node, result);
return result;
}
private convertJSXNamespaceOrIdentifier(
node: ts.Identifier | ts.ThisExpression,
): TSESTree.JSXIdentifier | TSESTree.JSXNamespacedName {
const text = node.getText();
const colonIndex = text.indexOf(':');
// this is intentional we can ignore conversion if `:` is in first character
if (colonIndex > 0) {
const range = getRange(node, this.ast);
const result = this.createNode<TSESTree.JSXNamespacedName>(node, {
type: AST_NODE_TYPES.JSXNamespacedName,
namespace: this.createNode<TSESTree.JSXIdentifier>(node, {
type: AST_NODE_TYPES.JSXIdentifier,
name: text.slice(0, colonIndex),
range: [range[0], range[0] + colonIndex],
}),
name: this.createNode<TSESTree.JSXIdentifier>(node, {
type: AST_NODE_TYPES.JSXIdentifier,
name: text.slice(colonIndex + 1),
range: [range[0] + colonIndex + 1, range[1]],
}),
range,
});
this.registerTSNodeInNodeMap(node, result);
return result;
}
return this.convertJSXIdentifier(node);
}
/**
* 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.JSXTagNameExpression {
let result: TSESTree.JSXTagNameExpression;
switch (node.kind) {
case SyntaxKind.PropertyAccessExpression:
if (node.name.kind === SyntaxKind.PrivateIdentifier) {
// This is one of the few times where TS explicitly errors, and doesn't even gracefully handle the syntax.
// So we shouldn't ever get into this state to begin with.
throw new Error('Non-private identifier expected.');
}
result = this.createNode<TSESTree.JSXMemberExpression>(node, {
type: AST_NODE_TYPES.JSXMemberExpression,
object: this.convertJSXTagName(node.expression, parent),
property: this.convertJSXIdentifier(node.name),
});
break;
case SyntaxKind.ThisKeyword:
case SyntaxKind.Identifier:
default:
return this.convertJSXNamespaceOrIdentifier(node);
}
this.registerTSNodeInNodeMap(node, result);
return result;
}
private convertMethodSignature(
node:
| ts.MethodSignature
| ts.GetAccessorDeclaration
| ts.SetAccessorDeclaration,
): TSESTree.TSMethodSignature {
const result = this.createNode<TSESTree.TSMethodSignature>(node, {
type: AST_NODE_TYPES.TSMethodSignature,
computed: isComputedProperty(node.name),
key: this.convertChild(node.name),
params: this.convertParameters(node.parameters),
kind: ((): 'get' | 'set' | 'method' => {
switch (node.kind) {
case SyntaxKind.GetAccessor:
return 'get';
case SyntaxKind.SetAccessor:
return 'set';
case SyntaxKind.MethodSignature:
return 'method';
}
})(),
});
if (isOptional(node)) {
result.optional = true;
}
if (node.type) {
result.returnType = this.convertTypeAnnotation(node.type, node);
}
if (hasModifier(SyntaxKind.ReadonlyKeyword, node)) {
result.readonly = true;
}
if (node.typeParameters) {
result.typeParameters =
this.convertTSTypeParametersToTypeParametersDeclaration(
node.typeParameters,
);
}
const accessibility = getTSNodeAccessibility(node);
if (accessibility) {
result.accessibility = accessibility;
}
if (hasModifier(SyntaxKind.ExportKeyword, node)) {
result.export = true;
}
if (hasModifier(SyntaxKind.StaticKeyword, node)) {
result.static = true;
}
return result;
}
private convertAssertClasue(
node: ts.AssertClause | undefined,
): TSESTree.ImportAttribute[] {
return node === undefined
? []
: node.elements.map(element => this.convertChild(element));
}
/**
* 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);
}
}
private assertModuleSpecifier(
node: ts.ExportDeclaration | ts.ImportDeclaration,
allowNull: boolean,
): void {
if (!allowNull && node.moduleSpecifier == null) {
throw createError(
this.ast,
node.pos,
'Module specifier must be a string literal.',
);
}
if (
node.moduleSpecifier &&
node.moduleSpecifier?.kind !== SyntaxKind.StringLiteral
) {
throw createError(
this.ast,
node.moduleSpecifier.pos,
'Module specifier must be a string literal.',
);
}
}
/**
* 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: TSNode): 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),
sourceType: node.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: {
if (isThisInTypeQuery(node)) {
// special case for `typeof this.foo` - TS emits an Identifier for `this`
// but we want to treat it as a ThisExpression for consistency
return this.createNode<TSESTree.ThisExpression>(node, {
type: AST_NODE_TYPES.ThisExpression,
});
}
return this.createNode<TSESTree.Identifier>(node, {
type: AST_NODE_TYPES.Identifier,
name: node.text,
});
}
case SyntaxKind.PrivateIdentifier: {
return this.createNode<TSESTree.PrivateIdentifier>(node, {
type: AST_NODE_TYPES.PrivateIdentifier,
// typescript includes the `#` in the text
name: node.text.slice(1),
});
}
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.convertBindingNameWithTypeAnnotation(
node.variableDeclaration.name,
node.variableDeclaration.type,
)
: 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);
}
// Process typeParameters
if (node.typeParameters) {
result.typeParameters =
this.convertTSTypeParametersToTypeParametersDeclaration(
node.typeParameters,
);
}
if (isDeclare) {
result.declare = true;
}
// 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.convertBindingNameWithTypeAnnotation(
node.name,
node.type,
node,
),
init: this.convertChild(node.initializer),
});
if (node.exclamationToken) {
result.definite = true;
}
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,
* Pre 4.8 TS would include them in the AST, so we did as well.
* However as of 4.8 TS no longer includes it (as it is, well, invalid).
*
* So for consistency across versions, we no longer include it either.
*/
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, {