-
Notifications
You must be signed in to change notification settings - Fork 28
/
util.ts
1181 lines (1101 loc) · 51.1 KB
/
util.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
import * as ts from 'typescript';
import { NodeWrap } from './convert-ast';
import {
isBlockLike, isLiteralExpression, isPropertyDeclaration, isJsDoc, isImportDeclaration, isTextualLiteral,
isImportEqualsDeclaration, isModuleDeclaration, isCallExpression, isExportDeclaration, isImportTypeNode, isLiteralTypeNode,
} from '../typeguard/node';
// TODO remove on v3.0.0
export * from './control-flow';
export function getChildOfKind<T extends ts.SyntaxKind>(node: ts.Node, kind: T, sourceFile?: ts.SourceFile) {
for (const child of node.getChildren(sourceFile))
if (child.kind === kind)
return <ts.Token<T>>child;
}
export function isTokenKind(kind: ts.SyntaxKind) {
return kind >= ts.SyntaxKind.FirstToken && kind <= ts.SyntaxKind.LastToken;
}
export function isNodeKind(kind: ts.SyntaxKind) {
return kind >= ts.SyntaxKind.FirstNode;
}
export function isAssignmentKind(kind: ts.SyntaxKind) {
return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment;
}
export function isTypeNodeKind(kind: ts.SyntaxKind) {
return kind >= ts.SyntaxKind.FirstTypeNode && kind <= ts.SyntaxKind.LastTypeNode;
}
export function isJsDocKind(kind: ts.SyntaxKind) {
return kind >= ts.SyntaxKind.FirstJSDocNode && kind <= ts.SyntaxKind.LastJSDocNode;
}
export function isThisParameter(parameter: ts.ParameterDeclaration): boolean {
return parameter.name.kind === ts.SyntaxKind.Identifier && parameter.name.originalKeywordKind === ts.SyntaxKind.ThisKeyword;
}
export function getModifier(node: ts.Node, kind: ts.Modifier['kind']): ts.Modifier | undefined {
if (node.modifiers !== undefined)
for (const modifier of node.modifiers)
if (modifier.kind === kind)
return modifier;
}
export function hasModifier(modifiers: ts.ModifiersArray | undefined, ...kinds: Array<ts.Modifier['kind']>) {
if (modifiers === undefined)
return false;
for (const modifier of modifiers)
if (kinds.indexOf(modifier.kind) !== -1)
return true;
return false;
}
export function isParameterProperty(node: ts.ParameterDeclaration) {
return hasModifier(node.modifiers,
ts.SyntaxKind.PublicKeyword,
ts.SyntaxKind.ProtectedKeyword,
ts.SyntaxKind.PrivateKeyword,
ts.SyntaxKind.ReadonlyKeyword);
}
export function hasAccessModifier(node: ts.ClassElement | ts.ParameterDeclaration) {
return hasModifier(node.modifiers,
ts.SyntaxKind.PublicKeyword,
ts.SyntaxKind.ProtectedKeyword,
ts.SyntaxKind.PrivateKeyword);
}
function isFlagSet(obj: {flags: number}, flag: number) {
return (obj.flags & flag) !== 0;
}
export const isNodeFlagSet: (node: ts.Node, flag: ts.NodeFlags) => boolean = isFlagSet;
export const isTypeFlagSet: (type: ts.Type, flag: ts.TypeFlags) => boolean = isFlagSet;
export const isSymbolFlagSet: (symbol: ts.Symbol, flag: ts.SymbolFlags) => boolean = isFlagSet;
export function isObjectFlagSet(objectType: ts.ObjectType, flag: ts.ObjectFlags) {
return (objectType.objectFlags & flag) !== 0;
}
export function isModifierFlagSet(node: ts.Node, flag: ts.ModifierFlags) {
return (ts.getCombinedModifierFlags(node) & flag) !== 0;
}
/**
* @deprecated Use isModifierFlagSet.
*/
export function isModfierFlagSet(node: ts.Node, flag: ts.ModifierFlags) {
return isModifierFlagSet(node, flag);
}
export function getPreviousStatement(statement: ts.Statement): ts.Statement | undefined {
const parent = statement.parent!;
if (isBlockLike(parent)) {
const index = parent.statements.indexOf(statement);
if (index > 0)
return parent.statements[index - 1];
}
}
export function getNextStatement(statement: ts.Statement): ts.Statement | undefined {
const parent = statement.parent!;
if (isBlockLike(parent)) {
const index = parent.statements.indexOf(statement);
if (index < parent.statements.length)
return parent.statements[index + 1];
}
}
/** Returns the token before the start of `node` or `undefined` if there is none. */
export function getPreviousToken(node: ts.Node, sourceFile?: ts.SourceFile) {
let parent = node.parent;
while (parent !== undefined && parent.pos === node.pos)
parent = parent.parent;
if (parent === undefined)
return;
outer: while (true) {
const children = parent.getChildren(sourceFile);
for (let i = children.length - 1; i >= 0; --i) {
const child = children[i];
if (child.pos < node.pos && child.kind !== ts.SyntaxKind.JSDocComment) {
if (isTokenKind(child.kind))
return child;
// previous token is nested in another node
parent = child;
continue outer;
}
}
return;
}
}
/** Returns the next token that begins after the end of `node`. Returns `undefined` for SourceFile and EndOfFileToken */
export function getNextToken(node: ts.Node, sourceFile = node.getSourceFile()) {
if (node.kind === ts.SyntaxKind.SourceFile || node.kind === ts.SyntaxKind.EndOfFileToken)
return;
const end = node.end;
node = node.parent!;
while (node.end === end) {
if (node.parent === undefined)
return (<ts.SourceFile>node).endOfFileToken;
node = node.parent;
}
return getTokenAtPositionWorker(node, end, sourceFile);
}
/** Returns the token at or following the specified position or undefined if none is found inside `parent`. */
export function getTokenAtPosition(parent: ts.Node, pos: number, sourceFile?: ts.SourceFile) {
if (pos < parent.pos || pos >= parent.end)
return;
if (isTokenKind(parent.kind))
return parent;
if (sourceFile === undefined)
sourceFile = parent.getSourceFile();
return getTokenAtPositionWorker(parent, pos, sourceFile);
}
function getTokenAtPositionWorker(node: ts.Node, pos: number, sourceFile: ts.SourceFile) {
outer: while (true) {
for (const child of node.getChildren(sourceFile)) {
if (child.end > pos && child.kind !== ts.SyntaxKind.JSDocComment) {
if (isTokenKind(child.kind))
return child;
// next token is nested in another node
node = child;
continue outer;
}
}
return;
}
}
/**
* Return the comment at the specified position.
* You can pass an optional `parent` to avoid some work finding the corresponding token starting at `sourceFile`.
* If the `parent` parameter is passed, `pos` must be between `parent.pos` and `parent.end`.
*/
export function getCommentAtPosition(sourceFile: ts.SourceFile, pos: number, parent: ts.Node = sourceFile): ts.CommentRange | undefined {
const token = getTokenAtPosition(parent, pos, sourceFile);
if (token === undefined || token.kind === ts.SyntaxKind.JsxText || pos >= token.end - (ts.tokenToString(token.kind) || '').length)
return;
const startPos = token.pos === 0
? (ts.getShebang(sourceFile.text) || '').length
: token.pos ;
return startPos !== 0 && ts.forEachTrailingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos) ||
ts.forEachLeadingCommentRange(sourceFile.text, startPos, commentAtPositionCallback, pos);
}
function commentAtPositionCallback(pos: number, end: number, kind: ts.CommentKind, _nl: boolean, at: number): ts.CommentRange | undefined {
return at >= pos && at < end ? {pos, end, kind} : undefined;
}
/**
* Returns whether the specified position is inside a comment.
* You can pass an optional `parent` to avoid some work finding the corresponding token starting at `sourceFile`.
* If the `parent` parameter is passed, `pos` must be between `parent.pos` and `parent.end`.
*/
export function isPositionInComment(sourceFile: ts.SourceFile, pos: number, parent?: ts.Node): boolean {
return getCommentAtPosition(sourceFile, pos, parent) !== undefined;
}
/**
* Returns the NodeWrap of deepest AST node that contains `pos` between its `pos` and `end`.
* Only returns undefined if pos is outside of `wrap`
*/
export function getWrappedNodeAtPosition(wrap: NodeWrap, pos: number): NodeWrap | undefined {
if (wrap.node.pos > pos || wrap.node.end <= pos)
return;
outer: while (true) {
for (const child of wrap.children) {
if (child.node.pos > pos)
return wrap;
if (child.node.end > pos) {
wrap = child;
continue outer;
}
}
return wrap;
}
}
export function getPropertyName(propertyName: ts.PropertyName): string | undefined {
if (propertyName.kind === ts.SyntaxKind.ComputedPropertyName) {
if (!isLiteralExpression(propertyName.expression))
return;
return propertyName.expression.text;
}
return propertyName.kind === ts.SyntaxKind.Identifier ? getIdentifierText(propertyName) : propertyName.text;
}
export function forEachDestructuringIdentifier<T>(
pattern: ts.BindingPattern,
fn: (element: ts.BindingElement & { name: ts.Identifier }) => T,
): T | undefined {
for (const element of pattern.elements) {
if (element.kind !== ts.SyntaxKind.BindingElement)
continue;
let result: T | undefined;
if (element.name.kind === ts.SyntaxKind.Identifier) {
result = fn(<ts.BindingElement & { name: ts.Identifier }>element);
} else {
result = forEachDestructuringIdentifier(element.name, fn);
}
if (result)
return result;
}
}
export function forEachDeclaredVariable<T>(
declarationList: ts.VariableDeclarationList,
cb: (element: (ts.VariableDeclaration | ts.BindingElement) & { name: ts.Identifier }) => T,
) {
for (const declaration of declarationList.declarations) {
let result: T | undefined;
if (declaration.name.kind === ts.SyntaxKind.Identifier) {
result = cb(<ts.VariableDeclaration & { name: ts.Identifier }>declaration);
} else {
result = forEachDestructuringIdentifier(declaration.name, cb);
}
if (result)
return result;
}
}
export const enum VariableDeclarationKind {
Var,
Let,
Const,
}
export function getVariableDeclarationKind(declarationList: ts.VariableDeclarationList): VariableDeclarationKind {
if (declarationList.flags & ts.NodeFlags.Let)
return VariableDeclarationKind.Let;
if (declarationList.flags & ts.NodeFlags.Const)
return VariableDeclarationKind.Const;
return VariableDeclarationKind.Var;
}
export function isBlockScopedVariableDeclarationList(declarationList: ts.VariableDeclarationList): boolean {
return (declarationList.flags & ts.NodeFlags.BlockScoped) !== 0;
}
export function isBlockScopedVariableDeclaration(declaration: ts.VariableDeclaration): boolean {
const parent = declaration.parent!;
return parent.kind === ts.SyntaxKind.CatchClause ||
isBlockScopedVariableDeclarationList(parent);
}
export const enum ScopeBoundary {
None,
Function,
Block,
}
export function isScopeBoundary(node: ts.Node): ScopeBoundary {
if (isFunctionScopeBoundary(node))
return ScopeBoundary.Function;
if (isBlockScopeBoundary(node))
return ScopeBoundary.Block;
return ScopeBoundary.None;
}
export function isFunctionScopeBoundary(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.Constructor:
case ts.SyntaxKind.ModuleDeclaration:
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.ClassExpression:
case ts.SyntaxKind.EnumDeclaration:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.TypeAliasDeclaration:
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.CallSignature:
case ts.SyntaxKind.ConstructSignature:
case ts.SyntaxKind.ConstructorType:
case ts.SyntaxKind.FunctionType:
case ts.SyntaxKind.MappedType:
case ts.SyntaxKind.ConditionalType:
return true;
case ts.SyntaxKind.SourceFile:
// if SourceFile is no module, it contributes to the global scope and is therefore no scope boundary
return ts.isExternalModule(<ts.SourceFile>node);
default:
return false;
}
}
export function isBlockScopeBoundary(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.Block:
const parent = node.parent!;
return parent.kind !== ts.SyntaxKind.CatchClause &&
// blocks inside SourceFile are block scope boundaries
(parent.kind === ts.SyntaxKind.SourceFile ||
// blocks that are direct children of a function scope boundary are no scope boundary
// for example the FunctionBlock is part of the function scope of the containing function
!isFunctionScopeBoundary(parent));
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.ForInStatement:
case ts.SyntaxKind.ForOfStatement:
case ts.SyntaxKind.CaseBlock:
case ts.SyntaxKind.CatchClause:
return true;
default:
return false;
}
}
/** Returns true for scope boundaries that have their own `this` reference instead of inheriting it from the containing scope */
export function hasOwnThisReference(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.ClassExpression:
case ts.SyntaxKind.FunctionExpression:
return true;
case ts.SyntaxKind.FunctionDeclaration:
return (<ts.FunctionDeclaration>node).body !== undefined;
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
return node.parent!.kind === ts.SyntaxKind.ObjectLiteralExpression;
default:
return false;
}
}
export function isFunctionWithBody(node: ts.Node): node is ts.FunctionLikeDeclaration {
switch (node.kind) {
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.Constructor:
return (<ts.FunctionLikeDeclaration>node).body !== undefined;
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.ArrowFunction:
return true;
default:
return false;
}
}
/**
* Iterate over all tokens of `node`
*
* @param node The node whose tokens should be visited
* @param cb Is called for every token contained in `node`
*/
export function forEachToken(node: ts.Node, cb: (node: ts.Node) => void, sourceFile: ts.SourceFile = node.getSourceFile()) {
return (function iterate(child): void {
if (isTokenKind(child.kind))
return cb(child); // tokens have no children -> no need to recurse deeper
/* Exclude everything contained in JsDoc, it will be handled with the other trivia anyway.
* When we would handle JsDoc tokens like regular ones, we would scan some trivia multiple times.
* Even worse, we would scan for trivia inside the JsDoc comment, which yields unexpected results.*/
if (child.kind !== ts.SyntaxKind.JSDocComment)
return child.getChildren(sourceFile).forEach(iterate);
})(node);
}
export type ForEachTokenCallback = (fullText: string, kind: ts.SyntaxKind, range: ts.TextRange, parent: ts.Node) => void;
/**
* Iterate over all tokens and trivia of `node`
*
* @description JsDoc comments are treated like regular comments
*
* @param node The node whose tokens should be visited
* @param cb Is called for every token contained in `node` and trivia before the token
*/
export function forEachTokenWithTrivia(node: ts.Node, cb: ForEachTokenCallback, sourceFile: ts.SourceFile = node.getSourceFile()) {
const fullText = sourceFile.text;
const scanner = ts.createScanner(sourceFile.languageVersion, false, sourceFile.languageVariant, fullText);
return forEachToken(
node,
(token) => {
const tokenStart = token.kind === ts.SyntaxKind.JsxText || token.pos === token.end ? token.pos : token.getStart(sourceFile);
if (tokenStart !== token.pos) {
// we only have to handle trivia before each token. whitespace at the end of the file is followed by EndOfFileToken
scanner.setTextPos(token.pos);
let kind = scanner.scan();
let pos = scanner.getTokenPos();
while (pos < tokenStart) {
const textPos = scanner.getTextPos();
cb(fullText, kind, {pos, end: textPos}, token.parent!);
if (textPos === tokenStart)
break;
kind = scanner.scan();
pos = scanner.getTokenPos();
}
}
return cb(fullText, token.kind, {end: token.end, pos: tokenStart}, token.parent!);
},
sourceFile);
}
export type ForEachCommentCallback = (fullText: string, comment: ts.CommentRange) => void;
/** Iterate over all comments owned by `node` or its children */
export function forEachComment(node: ts.Node, cb: ForEachCommentCallback, sourceFile: ts.SourceFile = node.getSourceFile()) {
/* Visit all tokens and skip trivia.
Comment ranges between tokens are parsed without the need of a scanner.
forEachTokenWithWhitespace does intentionally not pay attention to the correct comment ownership of nodes as it always
scans all trivia before each token, which could include trailing comments of the previous token.
Comment onwership is done right in this function*/
const fullText = sourceFile.text;
const notJsx = sourceFile.languageVariant !== ts.LanguageVariant.JSX;
return forEachToken(
node,
(token) => {
if (token.pos === token.end)
return;
if (token.kind !== ts.SyntaxKind.JsxText)
ts.forEachLeadingCommentRange(
fullText,
// skip shebang at position 0
token.pos === 0 ? (ts.getShebang(fullText) || '').length : token.pos,
commentCallback,
);
if (notJsx || canHaveTrailingTrivia(token))
return ts.forEachTrailingCommentRange(fullText, token.end, commentCallback);
},
sourceFile,
);
function commentCallback(pos: number, end: number, kind: ts.CommentKind) {
cb(fullText, {pos, end, kind});
}
}
/** Exclude trailing positions that would lead to scanning for trivia inside JsxText */
function canHaveTrailingTrivia(token: ts.Node): boolean {
switch (token.kind) {
case ts.SyntaxKind.CloseBraceToken:
// after a JsxExpression inside a JsxElement's body can only be other JsxChild, but no trivia
return token.parent!.kind !== ts.SyntaxKind.JsxExpression || !isJsxElementOrFragment(token.parent!.parent!);
case ts.SyntaxKind.GreaterThanToken:
switch (token.parent!.kind) {
case ts.SyntaxKind.JsxOpeningElement:
// if end is not equal, this is part of the type arguments list. in all other cases it would be inside the element body
return token.end !== token.parent!.end;
case ts.SyntaxKind.JsxOpeningFragment:
return false; // would be inside the fragment
case ts.SyntaxKind.JsxSelfClosingElement:
return token.end !== token.parent!.end || // if end is not equal, this is part of the type arguments list
!isJsxElementOrFragment(token.parent!.parent!); // there's only trailing trivia if it's the end of the top element
case ts.SyntaxKind.JsxClosingElement:
case ts.SyntaxKind.JsxClosingFragment:
// there's only trailing trivia if it's the end of the top element
return !isJsxElementOrFragment(token.parent!.parent!.parent!);
}
}
return true;
}
function isJsxElementOrFragment(node: ts.Node): node is ts.JsxElement | ts.JsxFragment {
return node.kind === ts.SyntaxKind.JsxElement || node.kind === ts.SyntaxKind.JsxFragment;
}
export interface LineRange extends ts.TextRange {
contentLength: number;
}
export function getLineRanges(sourceFile: ts.SourceFile): LineRange[] {
const lineStarts = sourceFile.getLineStarts();
const result: LineRange[] = [];
const length = lineStarts.length;
const sourceText = sourceFile.text;
let pos = 0;
for (let i = 1; i < length; ++i) {
const end = lineStarts[i];
let lineEnd = end;
for (; lineEnd > pos; --lineEnd)
if (!ts.isLineBreak(sourceText.charCodeAt(lineEnd - 1)))
break;
result.push({
pos,
end,
contentLength: lineEnd - pos,
});
pos = end;
}
result.push({
pos,
end: sourceFile.end,
contentLength: sourceFile.end - pos,
});
return result;
}
/** Get the line break style used in sourceFile. This function only looks at the first line break. If there is none, \n is assumed. */
export function getLineBreakStyle(sourceFile: ts.SourceFile) {
const lineStarts = sourceFile.getLineStarts();
return lineStarts.length === 1 || lineStarts[1] < 2 || sourceFile.text[lineStarts[1] - 2] !== '\r'
? '\n'
: '\r\n';
}
let cachedScanner: ts.Scanner | undefined;
function scanToken(text: string) {
if (cachedScanner === undefined) // cache scanner
cachedScanner = ts.createScanner(ts.ScriptTarget.Latest, false);
cachedScanner.setText(text);
cachedScanner.scan();
return cachedScanner;
}
export function isValidIdentifier(text: string): boolean {
const scan = scanToken(text);
return scan.isIdentifier() && scan.getTextPos() === text.length && scan.getTokenPos() === 0;
}
export function isValidPropertyAccess(text: string): boolean {
if (!ts.isIdentifierStart(text.charCodeAt(0), ts.ScriptTarget.Latest))
return false;
for (let i = 1; i < text.length; ++i)
if (!ts.isIdentifierPart(text.charCodeAt(i), ts.ScriptTarget.Latest))
return false;
return true;
}
export function isValidPropertyName(text: string) {
if (isValidPropertyAccess(text))
return true;
const scan = scanToken(text);
return scan.getTextPos() === text.length &&
scan.getToken() === ts.SyntaxKind.NumericLiteral && scan.getTokenValue() === text; // ensure stringified number equals literal
}
export function isValidNumericLiteral(text: string): boolean {
const scan = scanToken(text);
return scan.getToken() === ts.SyntaxKind.NumericLiteral && scan.getTextPos() === text.length && scan.getTokenPos() === 0;
}
export function isSameLine(sourceFile: ts.SourceFile, pos1: number, pos2: number) {
return ts.getLineAndCharacterOfPosition(sourceFile, pos1).line === ts.getLineAndCharacterOfPosition(sourceFile, pos2).line;
}
export const enum SideEffectOptions {
None = 0,
TaggedTemplate = 1,
Constructor = 2,
JsxElement = 4,
}
export function hasSideEffects(node: ts.Expression, options?: SideEffectOptions): boolean {
switch (node.kind) {
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.PostfixUnaryExpression:
case ts.SyntaxKind.AwaitExpression:
case ts.SyntaxKind.YieldExpression:
case ts.SyntaxKind.DeleteExpression:
return true;
case ts.SyntaxKind.TypeAssertionExpression:
case ts.SyntaxKind.AsExpression:
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.NonNullExpression:
case ts.SyntaxKind.VoidExpression:
case ts.SyntaxKind.TypeOfExpression:
case ts.SyntaxKind.PropertyAccessExpression:
case ts.SyntaxKind.SpreadElement:
case ts.SyntaxKind.PartiallyEmittedExpression:
return hasSideEffects(
(<ts.AssertionExpression | ts.ParenthesizedExpression | ts.NonNullExpression | ts.VoidExpression | ts.TypeOfExpression |
ts.PropertyAccessExpression | ts.SpreadElement | ts.PartiallyEmittedExpression>node).expression,
options,
);
case ts.SyntaxKind.BinaryExpression:
return isAssignmentKind((<ts.BinaryExpression>node).operatorToken.kind) ||
hasSideEffects((<ts.BinaryExpression>node).left, options) ||
hasSideEffects((<ts.BinaryExpression>node).right, options);
case ts.SyntaxKind.PrefixUnaryExpression:
switch ((<ts.PrefixUnaryExpression>node).operator) {
case ts.SyntaxKind.PlusPlusToken:
case ts.SyntaxKind.MinusMinusToken:
return true;
default:
return hasSideEffects((<ts.PrefixUnaryExpression>node).operand, options);
}
case ts.SyntaxKind.ElementAccessExpression:
return hasSideEffects((<ts.ElementAccessExpression>node).expression, options) ||
// wotan-disable-next-line no-useless-predicate
(<ts.ElementAccessExpression>node).argumentExpression !== undefined && // for compatibility with typescript@<2.9.0
hasSideEffects((<ts.ElementAccessExpression>node).argumentExpression, options);
case ts.SyntaxKind.ConditionalExpression:
return hasSideEffects((<ts.ConditionalExpression>node).condition, options) ||
hasSideEffects((<ts.ConditionalExpression>node).whenTrue, options) ||
hasSideEffects((<ts.ConditionalExpression>node).whenFalse, options);
case ts.SyntaxKind.NewExpression:
if (options! & SideEffectOptions.Constructor || hasSideEffects((<ts.NewExpression>node).expression, options))
return true;
if ((<ts.NewExpression>node).arguments !== undefined)
for (const child of (<ts.NewExpression>node).arguments!)
if (hasSideEffects(child, options))
return true;
return false;
case ts.SyntaxKind.TaggedTemplateExpression:
if (options! & SideEffectOptions.TaggedTemplate || hasSideEffects((<ts.TaggedTemplateExpression>node).tag, options))
return true;
if ((<ts.TaggedTemplateExpression>node).template.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral)
return false;
node = (<ts.TaggedTemplateExpression>node).template;
// falls through
case ts.SyntaxKind.TemplateExpression:
for (const child of (<ts.TemplateExpression>node).templateSpans)
if (hasSideEffects(child.expression, options))
return true;
return false;
case ts.SyntaxKind.ClassExpression:
return classExpressionHasSideEffects(<ts.ClassExpression>node, options);
case ts.SyntaxKind.ArrayLiteralExpression:
for (const child of (<ts.ArrayLiteralExpression>node).elements)
if (hasSideEffects(child, options))
return true;
return false;
case ts.SyntaxKind.ObjectLiteralExpression:
for (const child of (<ts.ObjectLiteralExpression>node).properties) {
if (child.name !== undefined && child.name.kind === ts.SyntaxKind.ComputedPropertyName &&
hasSideEffects(child.name.expression, options))
return true;
switch (child.kind) {
case ts.SyntaxKind.PropertyAssignment:
if (hasSideEffects(child.initializer, options))
return true;
break;
case ts.SyntaxKind.SpreadAssignment:
if (hasSideEffects(child.expression, options))
return true;
}
}
return false;
case ts.SyntaxKind.JsxExpression:
return (<ts.JsxExpression>node).expression !== undefined && hasSideEffects((<ts.JsxExpression>node).expression!, options);
case ts.SyntaxKind.JsxElement:
case ts.SyntaxKind.JsxFragment:
for (const child of (<ts.JsxElement | ts.JsxFragment>node).children)
if (child.kind !== ts.SyntaxKind.JsxText && hasSideEffects(child, options))
return true;
if (node.kind === ts.SyntaxKind.JsxFragment)
return false;
node = (<ts.JsxElement>node).openingElement;
// falls through
case ts.SyntaxKind.JsxSelfClosingElement:
case ts.SyntaxKind.JsxOpeningElement:
if (options! & SideEffectOptions.JsxElement)
return true;
for (const child of getJsxAttributes(<ts.JsxOpeningLikeElement>node)) {
if (child.kind === ts.SyntaxKind.JsxSpreadAttribute) {
if (hasSideEffects(child.expression, options))
return true;
} else if (child.initializer !== undefined && hasSideEffects(child.initializer, options)) {
return true;
}
}
return false;
case ts.SyntaxKind.CommaListExpression:
for (const child of (<ts.CommaListExpression>node).elements)
if (hasSideEffects(child, options))
return true;
return false;
default:
return false;
}
}
function getJsxAttributes(openElement: ts.JsxOpeningLikeElement): ts.NodeArray<ts.JsxAttributeLike> {
// for back-compat with typescript@<2.3
const attributes: ts.NodeArray<ts.JsxAttributeLike> | ts.JsxAttributes = openElement.attributes;
return Array.isArray(attributes) ? attributes : attributes.properties;
}
function classExpressionHasSideEffects(node: ts.ClassExpression, options?: SideEffectOptions): boolean {
if (node.heritageClauses !== undefined && node.heritageClauses[0].token === ts.SyntaxKind.ExtendsKeyword)
for (const base of node.heritageClauses[0].types)
if (hasSideEffects(base.expression, options))
return true;
for (const child of node.members)
if (child.name !== undefined && child.name.kind === ts.SyntaxKind.ComputedPropertyName &&
hasSideEffects(child.name.expression, options) ||
isPropertyDeclaration(child) && child.initializer !== undefined &&
hasSideEffects(child.initializer, options))
return true;
return false;
}
/** Returns the VariableDeclaration or ParameterDeclaration that contains the BindingElement */
export function getDeclarationOfBindingElement(node: ts.BindingElement): ts.VariableDeclaration | ts.ParameterDeclaration {
let parent = node.parent!.parent!;
while (parent.kind === ts.SyntaxKind.BindingElement)
parent = parent.parent!.parent!;
return parent;
}
export function isExpressionValueUsed(node: ts.Expression): boolean {
while (true) {
const parent = node.parent!;
switch (parent.kind) {
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.NewExpression:
case ts.SyntaxKind.ElementAccessExpression:
case ts.SyntaxKind.WhileStatement:
case ts.SyntaxKind.DoStatement:
case ts.SyntaxKind.WithStatement:
case ts.SyntaxKind.ThrowStatement:
case ts.SyntaxKind.ReturnStatement:
case ts.SyntaxKind.JsxExpression:
case ts.SyntaxKind.JsxSpreadAttribute:
case ts.SyntaxKind.JsxElement:
case ts.SyntaxKind.JsxFragment:
case ts.SyntaxKind.JsxSelfClosingElement:
case ts.SyntaxKind.ComputedPropertyName:
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.ExportSpecifier:
case ts.SyntaxKind.ExportAssignment:
case ts.SyntaxKind.ImportDeclaration:
case ts.SyntaxKind.ExternalModuleReference:
case ts.SyntaxKind.Decorator:
case ts.SyntaxKind.TaggedTemplateExpression:
case ts.SyntaxKind.TemplateSpan:
case ts.SyntaxKind.ExpressionWithTypeArguments:
case ts.SyntaxKind.TypeOfExpression:
case ts.SyntaxKind.AwaitExpression:
case ts.SyntaxKind.YieldExpression:
case ts.SyntaxKind.LiteralType:
case ts.SyntaxKind.JsxAttributes:
case ts.SyntaxKind.JsxOpeningElement:
case ts.SyntaxKind.JsxClosingElement:
case ts.SyntaxKind.IfStatement:
case ts.SyntaxKind.CaseClause:
case ts.SyntaxKind.SwitchStatement:
return true;
case ts.SyntaxKind.PropertyAccessExpression:
return (<ts.PropertyAccessExpression>parent).expression === node;
case ts.SyntaxKind.QualifiedName:
return (<ts.QualifiedName>parent).left === node;
case ts.SyntaxKind.ShorthandPropertyAssignment:
return (<ts.ShorthandPropertyAssignment>parent).objectAssignmentInitializer === node ||
!isInDestructuringAssignment(<ts.ShorthandPropertyAssignment>parent);
case ts.SyntaxKind.PropertyAssignment:
return (<ts.PropertyAssignment>parent).initializer === node && !isInDestructuringAssignment(<ts.PropertyAssignment>parent);
case ts.SyntaxKind.SpreadAssignment:
case ts.SyntaxKind.SpreadElement:
case ts.SyntaxKind.ArrayLiteralExpression:
return !isInDestructuringAssignment(<ts.SpreadAssignment | ts.SpreadElement | ts.ArrayLiteralExpression>parent);
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.AsExpression:
case ts.SyntaxKind.TypeAssertionExpression:
case ts.SyntaxKind.PostfixUnaryExpression:
case ts.SyntaxKind.PrefixUnaryExpression:
case ts.SyntaxKind.NonNullExpression:
node = <ts.Expression>parent;
break;
case ts.SyntaxKind.ForStatement:
return (<ts.ForStatement>parent).condition === node;
case ts.SyntaxKind.ForInStatement:
case ts.SyntaxKind.ForOfStatement:
return (<ts.ForInStatement | ts.ForOfStatement>parent).expression === node;
case ts.SyntaxKind.ConditionalExpression:
if ((<ts.ConditionalExpression>parent).condition === node)
return true;
node = <ts.Expression>parent;
break;
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.BindingElement:
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.EnumMember:
return (<ts.HasExpressionInitializer>parent).initializer === node;
case ts.SyntaxKind.ImportEqualsDeclaration:
return (<ts.ImportEqualsDeclaration>parent).moduleReference === node;
case ts.SyntaxKind.CommaListExpression:
if ((<ts.CommaListExpression>parent).elements[(<ts.CommaListExpression>parent).elements.length - 1] !== node)
return false;
node = <ts.Expression>parent;
break;
case ts.SyntaxKind.BinaryExpression:
if ((<ts.BinaryExpression>parent).right === node) {
if ((<ts.BinaryExpression>parent).operatorToken.kind === ts.SyntaxKind.CommaToken) {
node = <ts.Expression>parent;
break;
}
return true;
}
switch ((<ts.BinaryExpression>parent).operatorToken.kind) {
case ts.SyntaxKind.CommaToken:
case ts.SyntaxKind.EqualsToken:
return false;
case ts.SyntaxKind.EqualsEqualsEqualsToken:
case ts.SyntaxKind.EqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsToken:
case ts.SyntaxKind.InstanceOfKeyword:
case ts.SyntaxKind.PlusToken:
case ts.SyntaxKind.MinusToken:
case ts.SyntaxKind.AsteriskToken:
case ts.SyntaxKind.SlashToken:
case ts.SyntaxKind.PercentToken:
case ts.SyntaxKind.AsteriskAsteriskToken:
case ts.SyntaxKind.GreaterThanToken:
case ts.SyntaxKind.GreaterThanGreaterThanToken:
case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
case ts.SyntaxKind.GreaterThanEqualsToken:
case ts.SyntaxKind.LessThanToken:
case ts.SyntaxKind.LessThanLessThanToken:
case ts.SyntaxKind.LessThanEqualsToken:
case ts.SyntaxKind.AmpersandToken:
case ts.SyntaxKind.BarToken:
case ts.SyntaxKind.CaretToken:
case ts.SyntaxKind.BarBarToken:
case ts.SyntaxKind.AmpersandAmpersandToken:
case ts.SyntaxKind.InKeyword:
return true;
default:
node = <ts.Expression>parent;
}
break;
default:
return false;
}
}
}
function isInDestructuringAssignment(
node: ts.PropertyAssignment | ts.ShorthandPropertyAssignment | ts.SpreadAssignment | ts.SpreadElement |
ts.ObjectLiteralExpression | ts.ArrayLiteralExpression,
): boolean {
switch (node.kind) {
case ts.SyntaxKind.ShorthandPropertyAssignment:
if (node.objectAssignmentInitializer !== undefined)
return true;
// falls through
case ts.SyntaxKind.PropertyAssignment:
case ts.SyntaxKind.SpreadAssignment:
node = <ts.ArrayLiteralExpression | ts.ObjectLiteralExpression>node.parent;
break;
case ts.SyntaxKind.SpreadElement:
if (node.parent!.kind !== ts.SyntaxKind.ArrayLiteralExpression)
return false;
node = <ts.ArrayLiteralExpression>node.parent;
}
while (true) {
switch (node.parent!.kind) {
case ts.SyntaxKind.BinaryExpression:
return (<ts.BinaryExpression>node.parent).left === node &&
(<ts.BinaryExpression>node.parent).operatorToken.kind === ts.SyntaxKind.EqualsToken;
case ts.SyntaxKind.ForOfStatement:
return (<ts.ForOfStatement>node.parent).initializer === node;
case ts.SyntaxKind.ArrayLiteralExpression:
case ts.SyntaxKind.ObjectLiteralExpression:
node = <ts.ArrayLiteralExpression | ts.ObjectLiteralExpression>node.parent;
break;
case ts.SyntaxKind.SpreadAssignment:
case ts.SyntaxKind.PropertyAssignment:
node = <ts.ObjectLiteralExpression>node.parent!.parent;
break;
case ts.SyntaxKind.SpreadElement:
if (node.parent!.parent!.kind !== ts.SyntaxKind.ArrayLiteralExpression)
return false;
node = <ts.ArrayLiteralExpression>node.parent!.parent;
break;
default:
return false;
}
}
}
export function isReassignmentTarget(node: ts.Expression): boolean {
const parent = node.parent!;
switch (parent.kind) {
case ts.SyntaxKind.PostfixUnaryExpression:
case ts.SyntaxKind.DeleteExpression:
return true;
case ts.SyntaxKind.PrefixUnaryExpression:
return (<ts.PrefixUnaryExpression>parent).operator === ts.SyntaxKind.PlusPlusToken ||
(<ts.PrefixUnaryExpression>parent).operator === ts.SyntaxKind.MinusMinusToken;
case ts.SyntaxKind.BinaryExpression:
return (<ts.BinaryExpression>parent).left === node &&
isAssignmentKind((<ts.BinaryExpression>parent).operatorToken.kind);
case ts.SyntaxKind.ShorthandPropertyAssignment:
return (<ts.ShorthandPropertyAssignment>parent).name === node &&
isInDestructuringAssignment(<ts.ShorthandPropertyAssignment>parent);
case ts.SyntaxKind.PropertyAssignment:
return (<ts.PropertyAssignment>parent).initializer === node &&
isInDestructuringAssignment(<ts.PropertyAssignment>parent);
case ts.SyntaxKind.ArrayLiteralExpression:
case ts.SyntaxKind.SpreadElement:
case ts.SyntaxKind.SpreadAssignment:
return isInDestructuringAssignment(<ts.SpreadElement | ts.SpreadAssignment | ts.ArrayLiteralExpression>parent);
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.NonNullExpression:
case ts.SyntaxKind.TypeAssertionExpression:
case ts.SyntaxKind.AsExpression:
// (<number>foo! as {})++
return isReassignmentTarget(<ts.Expression>parent); // this assertion is not correct, but necessary to keep the API sane
case ts.SyntaxKind.ForOfStatement:
case ts.SyntaxKind.ForInStatement:
return (<ts.ForOfStatement | ts.ForInStatement>parent).initializer === node;
}
return false;
}
/**
* Safely gets the text of an identifier across typescript versions
* @param node The identifier to get the text of
*/
export function getIdentifierText(node: ts.Identifier) {
return ts.unescapeIdentifier(node.text); // wotan-disable-line no-unstable-api-use
}
export function canHaveJsDoc(node: ts.Node): node is ts.HasJSDoc {
const kind = (<ts.HasJSDoc>node).kind;
switch (kind) {
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.CallSignature:
case ts.SyntaxKind.ConstructSignature:
case ts.SyntaxKind.MethodSignature:
case ts.SyntaxKind.PropertySignature:
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.SpreadAssignment:
case ts.SyntaxKind.ShorthandPropertyAssignment:
case ts.SyntaxKind.PropertyAssignment:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.LabeledStatement:
case ts.SyntaxKind.ExpressionStatement:
case ts.SyntaxKind.VariableStatement:
case ts.SyntaxKind.Constructor:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.ClassExpression:
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.TypeAliasDeclaration:
case ts.SyntaxKind.EnumMember:
case ts.SyntaxKind.EnumDeclaration:
case ts.SyntaxKind.ModuleDeclaration:
case ts.SyntaxKind.ImportEqualsDeclaration:
case ts.SyntaxKind.IndexSignature:
case ts.SyntaxKind.FunctionType:
case ts.SyntaxKind.ConstructorType:
case ts.SyntaxKind.JSDocFunctionType:
case ts.SyntaxKind.EndOfFileToken:
return true;
default:
return <AssertNever<typeof kind>>false;
}
}
type AssertNever<T extends never> = T;
/** Gets the JSDoc of any node. For performance reasons this function should only be called when `canHaveJsDoc` return true. */
export function getJsDoc(node: ts.Node, sourceFile?: ts.SourceFile): ts.JSDoc[] {