-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
Copy pathtextChanges.ts
1869 lines (1676 loc) · 85.2 KB
/
textChanges.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 {
ArrowFunction,
BindingElement,
CharacterCodes,
ClassElement,
ClassExpression,
ClassLikeDeclaration,
CommentRange,
concatenate,
ConstructorDeclaration,
contains,
createMultiMap,
createNodeFactory,
createPrinter,
createRange,
createSourceFile,
createTextChange,
createTextRangeFromSpan,
createTextSpan,
createTextSpanFromRange,
createTextWriter,
Debug,
DeclarationStatement,
EmitHint,
EmitTextWriter,
endsWith,
EnumDeclaration,
EnumMember,
Expression,
factory,
FileTextChanges,
filter,
find,
findChildOfKind,
findLastIndex,
findNextToken,
findPrecedingToken,
first,
firstOrUndefined,
flatMap,
flatMapToMutable,
formatting,
FunctionDeclaration,
FunctionExpression,
getAncestor,
getFirstNonSpaceCharacterPosition,
getFormatCodeSettingsForWriting,
getJSDocCommentRanges,
getLeadingCommentRanges,
getLineAndCharacterOfPosition,
getLineOfLocalPosition,
getLineStartPositionForPosition,
getNewLineKind,
getNewLineOrDefaultFromHost,
getNodeId,
getOriginalNode,
getPrecedingNonSpaceCharacterPosition,
getScriptKindFromFileName,
getShebang,
getSourceFileOfNode,
getStartPositionOfLine,
getTokenAtPosition,
getTouchingToken,
getTrailingCommentRanges,
group,
HasJSDoc,
hasJSDocNodes,
ImportClause,
ImportSpecifier,
indexOfNode,
InterfaceDeclaration,
intersperse,
isAnyImportSyntax,
isArray,
isArrowFunction,
isCallExpression,
isClassElement,
isClassOrTypeElement,
isExpressionStatement,
isFunctionDeclaration,
isFunctionExpression,
isFunctionLike,
isIdentifier,
isImportClause,
isImportDeclaration,
isImportSpecifier,
isInComment,
isInJSXText,
isInString,
isInTemplateString,
isInterfaceDeclaration,
isJsonSourceFile,
isLineBreak,
isNamedImports,
isObjectLiteralExpression,
isParameter,
isPinnedComment,
isPrologueDirective,
isPropertyDeclaration,
isPropertySignature,
isRecognizedTripleSlashComment,
isStatement,
isStatementButNotDeclaration,
isString,
isStringLiteral,
isSuperCall,
isVariableDeclaration,
isWhiteSpaceLike,
isWhiteSpaceSingleLine,
JSDoc,
JSDocComment,
JSDocParameterTag,
JSDocParsingMode,
JSDocReturnTag,
JSDocTag,
JSDocTypeTag,
LanguageServiceHost,
last,
lastOrUndefined,
length,
mapDefined,
MethodSignature,
Modifier,
MultiMap,
NamedImportBindings,
NamedImports,
NamespaceImport,
Node,
NodeArray,
NodeFactoryFlags,
nodeIsSynthesized,
nullTransformationContext,
ObjectLiteralElementLike,
ObjectLiteralExpression,
ParameterDeclaration,
positionsAreOnSameLine,
PrintHandlers,
PrologueDirective,
PropertyAssignment,
PropertyDeclaration,
PropertySignature,
rangeContainsPosition,
rangeContainsRangeExclusive,
rangeOfNode,
rangeOfTypeParameters,
rangeStartPositionsAreOnSameLine,
removeSuffix,
ScriptKind,
ScriptTarget,
setTextRangePosEnd,
SignatureDeclaration,
singleOrUndefined,
skipTrivia,
SourceFile,
SourceFileLike,
Statement,
stringContainsAt,
Symbol,
SyntaxKind,
TextChange,
TextRange,
textSpanEnd,
Token,
tokenToString,
toSorted,
TransformationContext,
TypeLiteralNode,
TypeNode,
TypeParameterDeclaration,
UserPreferences,
VariableDeclaration,
VariableStatement,
visitEachChild,
visitNodes,
Visitor,
} from "./_namespaces/ts.js";
/**
* Currently for simplicity we store recovered positions on the node itself.
* It can be changed to side-table later if we decide that current design is too invasive.
*/
function getPos(n: TextRange): number {
const result = (n as any).__pos;
Debug.assert(typeof result === "number");
return result;
}
function setPos(n: TextRange, pos: number): void {
Debug.assert(typeof pos === "number");
(n as any).__pos = pos;
}
function getEnd(n: TextRange): number {
const result = (n as any).__end;
Debug.assert(typeof result === "number");
return result;
}
function setEnd(n: TextRange, end: number): void {
Debug.assert(typeof end === "number");
(n as any).__end = end;
}
/** @internal */
export interface ConfigurableStart {
leadingTriviaOption?: LeadingTriviaOption;
}
/** @internal */
export interface ConfigurableEnd {
trailingTriviaOption?: TrailingTriviaOption;
}
/** @internal */
export enum LeadingTriviaOption {
/** Exclude all leading trivia (use getStart()) */
Exclude,
/** Include leading trivia and,
* if there are no line breaks between the node and the previous token,
* include all trivia between the node and the previous token
*/
IncludeAll,
/**
* Include attached JSDoc comments
*/
JSDoc,
/**
* Only delete trivia on the same line as getStart().
* Used to avoid deleting leading comments
*/
StartLine,
}
/** @internal */
export enum TrailingTriviaOption {
/** Exclude all trailing trivia (use getEnd()) */
Exclude,
/** Doesn't include whitespace, but does strip comments */
ExcludeWhitespace,
/** Include trailing trivia */
Include,
}
function skipWhitespacesAndLineBreaks(text: string, start: number) {
return skipTrivia(text, start, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
}
function hasCommentsBeforeLineBreak(text: string, start: number) {
let i = start;
while (i < text.length) {
const ch = text.charCodeAt(i);
if (isWhiteSpaceSingleLine(ch)) {
i++;
continue;
}
return ch === CharacterCodes.slash;
}
return false;
}
/**
* Usually node.pos points to a position immediately after the previous token.
* If this position is used as a beginning of the span to remove - it might lead to removing the trailing trivia of the previous node, i.e:
* const x; // this is x
* ^ - pos for the next variable declaration will point here
* const y; // this is y
* ^ - end for previous variable declaration
* Usually leading trivia of the variable declaration 'y' should not include trailing trivia (whitespace, comment 'this is x' and newline) from the preceding
* variable declaration and trailing trivia for 'y' should include (whitespace, comment 'this is y', newline).
* By default when removing nodes we adjust start and end positions to respect specification of the trivia above.
* If pos\end should be interpreted literally (that is, withouth including leading and trailing trivia), `leadingTriviaOption` should be set to `LeadingTriviaOption.Exclude`
* and `trailingTriviaOption` to `TrailingTriviaOption.Exclude`.
*
* @internal
*/
export interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd {}
const useNonAdjustedPositions: ConfigurableStartEnd = {
leadingTriviaOption: LeadingTriviaOption.Exclude,
trailingTriviaOption: TrailingTriviaOption.Exclude,
};
/** @internal */
export interface InsertNodeOptions {
/**
* Text to be inserted before the new node
*/
prefix?: string;
/**
* Text to be inserted after the new node
*/
suffix?: string;
/**
* Text of inserted node will be formatted with this indentation, otherwise indentation will be inferred from the old node
*/
indentation?: number;
/**
* Text of inserted node will be formatted with this delta, otherwise delta will be inferred from the new node kind
*/
delta?: number;
}
/** @internal */
export interface ReplaceWithMultipleNodesOptions extends InsertNodeOptions {
readonly joiner?: string;
}
enum ChangeKind {
Remove,
ReplaceWithSingleNode,
ReplaceWithMultipleNodes,
Text,
}
type Change = ReplaceWithSingleNode | ReplaceWithMultipleNodes | RemoveNode | ChangeText;
interface BaseChange {
readonly sourceFile: SourceFile;
readonly range: TextRange;
}
/** @internal */
export interface ChangeNodeOptions extends ConfigurableStartEnd, InsertNodeOptions {}
interface ReplaceWithSingleNode extends BaseChange {
readonly kind: ChangeKind.ReplaceWithSingleNode;
readonly node: Node;
readonly options?: InsertNodeOptions;
}
interface RemoveNode extends BaseChange {
readonly kind: ChangeKind.Remove;
readonly node?: never;
readonly options?: never;
}
interface ReplaceWithMultipleNodes extends BaseChange {
readonly kind: ChangeKind.ReplaceWithMultipleNodes;
readonly nodes: readonly Node[];
readonly options?: ReplaceWithMultipleNodesOptions;
}
interface ChangeText extends BaseChange {
readonly kind: ChangeKind.Text;
readonly text: string;
}
interface NewFileInsertion {
readonly oldFile?: SourceFile;
readonly statements: readonly (Statement | SyntaxKind.NewLineTrivia)[];
}
function getAdjustedRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd): TextRange {
return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) };
}
function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd, hasTrailingComment = false): number {
const { leadingTriviaOption } = options;
if (leadingTriviaOption === LeadingTriviaOption.Exclude) {
return node.getStart(sourceFile);
}
if (leadingTriviaOption === LeadingTriviaOption.StartLine) {
const startPos = node.getStart(sourceFile);
const pos = getLineStartPositionForPosition(startPos, sourceFile);
return rangeContainsPosition(node, pos) ? pos : startPos;
}
if (leadingTriviaOption === LeadingTriviaOption.JSDoc) {
const JSDocComments = getJSDocCommentRanges(node, sourceFile.text);
if (JSDocComments?.length) {
return getLineStartPositionForPosition(JSDocComments[0].pos, sourceFile);
}
}
const fullStart = node.getFullStart();
const start = node.getStart(sourceFile);
if (fullStart === start) {
return start;
}
const fullStartLine = getLineStartPositionForPosition(fullStart, sourceFile);
const startLine = getLineStartPositionForPosition(start, sourceFile);
if (startLine === fullStartLine) {
// full start and start of the node are on the same line
// a, b;
// ^ ^
// | start
// fullstart
// when b is replaced - we usually want to keep the leading trvia
// when b is deleted - we delete it
return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start;
}
// if node has a trailing comments, use comment end position as the text has already been included.
if (hasTrailingComment) {
// Check first for leading comments as if the node is the first import, we want to exclude the trivia;
// otherwise we get the trailing comments.
const comment = getLeadingCommentRanges(sourceFile.text, fullStart)?.[0] || getTrailingCommentRanges(sourceFile.text, fullStart)?.[0];
if (comment) {
return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true);
}
}
// get start position of the line following the line that contains fullstart position
// (but only if the fullstart isn't the very beginning of the file)
const nextLineStart = fullStart > 0 ? 1 : 0;
let adjustedStartPosition = getStartPositionOfLine(getLineOfLocalPosition(sourceFile, fullStartLine) + nextLineStart, sourceFile);
// skip whitespaces/newlines
adjustedStartPosition = skipWhitespacesAndLineBreaks(sourceFile.text, adjustedStartPosition);
return getStartPositionOfLine(getLineOfLocalPosition(sourceFile, adjustedStartPosition), sourceFile);
}
/** Return the end position of a multiline comment of it is on another line; otherwise returns `undefined`; */
function getEndPositionOfMultilineTrailingComment(sourceFile: SourceFile, node: Node, options: ConfigurableEnd): number | undefined {
const { end } = node;
const { trailingTriviaOption } = options;
if (trailingTriviaOption === TrailingTriviaOption.Include) {
// If the trailing comment is a multiline comment that extends to the next lines,
// return the end of the comment and track it for the next nodes to adjust.
const comments = getTrailingCommentRanges(sourceFile.text, end);
if (comments) {
const nodeEndLine = getLineOfLocalPosition(sourceFile, node.end);
for (const comment of comments) {
// Single line can break the loop as trivia will only be this line.
// Comments on subsequest lines are also ignored.
if (comment.kind === SyntaxKind.SingleLineCommentTrivia || getLineOfLocalPosition(sourceFile, comment.pos) > nodeEndLine) {
break;
}
// Get the end line of the comment and compare against the end line of the node.
// If the comment end line position and the multiline comment extends to multiple lines,
// then is safe to return the end position.
const commentEndLine = getLineOfLocalPosition(sourceFile, comment.end);
if (commentEndLine > nodeEndLine) {
return skipTrivia(sourceFile.text, comment.end, /*stopAfterLineBreak*/ true, /*stopAtComments*/ true);
}
}
}
}
return undefined;
}
/** @internal */
export function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd): number {
const { end } = node;
const { trailingTriviaOption } = options;
if (trailingTriviaOption === TrailingTriviaOption.Exclude) {
return end;
}
if (trailingTriviaOption === TrailingTriviaOption.ExcludeWhitespace) {
const comments = concatenate(getTrailingCommentRanges(sourceFile.text, end), getLeadingCommentRanges(sourceFile.text, end));
const realEnd = comments?.[comments.length - 1]?.end;
if (realEnd) {
return realEnd;
}
return end;
}
const multilineEndPosition = getEndPositionOfMultilineTrailingComment(sourceFile, node, options);
if (multilineEndPosition) {
return multilineEndPosition;
}
const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true);
return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)))
? newEnd
: end;
}
/**
* Checks if 'candidate' argument is a legal separator in the list that contains 'node' as an element
*/
function isSeparator(node: Node, candidate: Node | undefined): candidate is Token<SyntaxKind.CommaToken | SyntaxKind.SemicolonToken> {
return !!candidate && !!node.parent && (candidate.kind === SyntaxKind.CommaToken || (candidate.kind === SyntaxKind.SemicolonToken && node.parent.kind === SyntaxKind.ObjectLiteralExpression));
}
/** @internal */
export interface TextChangesContext {
host: LanguageServiceHost;
formatContext: formatting.FormatContext;
preferences: UserPreferences;
}
/** @internal */
export type TypeAnnotatable = SignatureDeclaration | VariableDeclaration | ParameterDeclaration | PropertyDeclaration | PropertySignature;
/** @internal */
export type ThisTypeAnnotatable = FunctionDeclaration | FunctionExpression;
/** @internal */
export function isThisTypeAnnotatable(containingFunction: SignatureDeclaration): containingFunction is ThisTypeAnnotatable {
return isFunctionExpression(containingFunction) || isFunctionDeclaration(containingFunction);
}
/** @internal */
export class ChangeTracker {
private readonly changes: Change[] = [];
private newFileChanges?: MultiMap<string, NewFileInsertion>;
private readonly classesWithNodesInsertedAtStart = new Map<number, { readonly node: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression | TypeLiteralNode | EnumDeclaration; readonly sourceFile: SourceFile; }>(); // Set<ClassDeclaration> implemented as Map<node id, ClassDeclaration>
private readonly deletedNodes: { readonly sourceFile: SourceFile; readonly node: Node | NodeArray<TypeParameterDeclaration>; }[] = [];
public static fromContext(context: TextChangesContext): ChangeTracker {
return new ChangeTracker(getNewLineOrDefaultFromHost(context.host, context.formatContext.options), context.formatContext);
}
public static with(context: TextChangesContext, cb: (tracker: ChangeTracker) => void): FileTextChanges[] {
const tracker = ChangeTracker.fromContext(context);
cb(tracker);
return tracker.getChanges();
}
/** Public for tests only. Other callers should use `ChangeTracker.with`. */
constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {}
public pushRaw(sourceFile: SourceFile, change: FileTextChanges): void {
Debug.assertEqual(sourceFile.fileName, change.fileName);
for (const c of change.textChanges) {
this.changes.push({
kind: ChangeKind.Text,
sourceFile,
text: c.newText,
range: createTextRangeFromSpan(c.span),
});
}
}
public deleteRange(sourceFile: SourceFile, range: TextRange): void {
this.changes.push({ kind: ChangeKind.Remove, sourceFile, range });
}
delete(sourceFile: SourceFile, node: Node | NodeArray<TypeParameterDeclaration>): void {
this.deletedNodes.push({ sourceFile, node });
}
/** Stop! Consider using `delete` instead, which has logic for deleting nodes from delimited lists. */
public deleteNode(sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void {
this.deleteRange(sourceFile, getAdjustedRange(sourceFile, node, node, options));
}
public deleteNodes(sourceFile: SourceFile, nodes: readonly Node[], options: ConfigurableStartEnd | undefined = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }, hasTrailingComment: boolean): void {
// When deleting multiple nodes we need to track if the end position is including multiline trailing comments.
for (const node of nodes) {
const pos = getAdjustedStartPosition(sourceFile, node, options, hasTrailingComment);
const end = getAdjustedEndPosition(sourceFile, node, options);
this.deleteRange(sourceFile, { pos, end });
hasTrailingComment = !!getEndPositionOfMultilineTrailingComment(sourceFile, node, options);
}
}
public deleteModifier(sourceFile: SourceFile, modifier: Modifier): void {
this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) });
}
public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void {
const startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
const endPosition = getAdjustedEndPosition(sourceFile, endNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void {
const startPosition = getAdjustedStartPosition(sourceFile, startNode, options);
const endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options);
this.deleteRange(sourceFile, { pos: startPosition, end: endPosition });
}
public replaceRange(sourceFile: SourceFile, range: TextRange, newNode: Node, options: InsertNodeOptions = {}): void {
this.changes.push({ kind: ChangeKind.ReplaceWithSingleNode, sourceFile, range, options, node: newNode });
}
public replaceNode(sourceFile: SourceFile, oldNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions): void {
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNode, options);
}
public replaceNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, newNode: Node, options: ChangeNodeOptions = useNonAdjustedPositions): void {
this.replaceRange(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNode, options);
}
private replaceRangeWithNodes(sourceFile: SourceFile, range: TextRange, newNodes: readonly Node[], options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = {}): void {
this.changes.push({ kind: ChangeKind.ReplaceWithMultipleNodes, sourceFile, range, options, nodes: newNodes });
}
public replaceNodeWithNodes(sourceFile: SourceFile, oldNode: Node, newNodes: readonly Node[], options: ChangeNodeOptions = useNonAdjustedPositions): void {
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, options), newNodes, options);
}
public replaceNodeWithText(sourceFile: SourceFile, oldNode: Node, text: string): void {
this.replaceRangeWithText(sourceFile, getAdjustedRange(sourceFile, oldNode, oldNode, useNonAdjustedPositions), text);
}
public replaceNodeRangeWithNodes(sourceFile: SourceFile, startNode: Node, endNode: Node, newNodes: readonly Node[], options: ReplaceWithMultipleNodesOptions & ConfigurableStartEnd = useNonAdjustedPositions): void {
this.replaceRangeWithNodes(sourceFile, getAdjustedRange(sourceFile, startNode, endNode, options), newNodes, options);
}
public nodeHasTrailingComment(sourceFile: SourceFile, oldNode: Node, configurableEnd: ConfigurableEnd = useNonAdjustedPositions): boolean {
return !!getEndPositionOfMultilineTrailingComment(sourceFile, oldNode, configurableEnd);
}
private nextCommaToken(sourceFile: SourceFile, node: Node): Node | undefined {
const next = findNextToken(node, node.parent, sourceFile);
return next && next.kind === SyntaxKind.CommaToken ? next : undefined;
}
public replacePropertyAssignment(sourceFile: SourceFile, oldNode: PropertyAssignment, newNode: PropertyAssignment): void {
const suffix = this.nextCommaToken(sourceFile, oldNode) ? "" : ("," + this.newLineCharacter);
this.replaceNode(sourceFile, oldNode, newNode, { suffix });
}
public insertNodeAt(sourceFile: SourceFile, pos: number, newNode: Node, options: InsertNodeOptions = {}): void {
this.replaceRange(sourceFile, createRange(pos), newNode, options);
}
private insertNodesAt(sourceFile: SourceFile, pos: number, newNodes: readonly Node[], options: ReplaceWithMultipleNodesOptions = {}): void {
this.replaceRangeWithNodes(sourceFile, createRange(pos), newNodes, options);
}
public insertNodeAtTopOfFile(sourceFile: SourceFile, newNode: Statement, blankLineBetween: boolean): void {
this.insertAtTopOfFile(sourceFile, newNode, blankLineBetween);
}
public insertNodesAtTopOfFile(sourceFile: SourceFile, newNodes: readonly Statement[], blankLineBetween: boolean): void {
this.insertAtTopOfFile(sourceFile, newNodes, blankLineBetween);
}
private insertAtTopOfFile(sourceFile: SourceFile, insert: Statement | readonly Statement[], blankLineBetween: boolean): void {
const pos = getInsertionPositionAtSourceFileTop(sourceFile);
const options = {
prefix: pos === 0 ? undefined : this.newLineCharacter,
suffix: (isLineBreak(sourceFile.text.charCodeAt(pos)) ? "" : this.newLineCharacter) + (blankLineBetween ? this.newLineCharacter : ""),
};
if (isArray(insert)) {
this.insertNodesAt(sourceFile, pos, insert, options);
}
else {
this.insertNodeAt(sourceFile, pos, insert, options);
}
}
public insertNodesAtEndOfFile(
sourceFile: SourceFile,
newNodes: readonly Statement[],
blankLineBetween: boolean,
): void {
this.insertAtEndOfFile(sourceFile, newNodes, blankLineBetween);
}
private insertAtEndOfFile(
sourceFile: SourceFile,
insert: readonly Statement[],
blankLineBetween: boolean,
): void {
const pos = sourceFile.end + 1;
const options = {
prefix: this.newLineCharacter,
suffix: this.newLineCharacter + (blankLineBetween ? this.newLineCharacter : ""),
};
this.insertNodesAt(sourceFile, pos, insert, options);
}
public insertStatementsInNewFile(fileName: string, statements: readonly (Statement | SyntaxKind.NewLineTrivia)[], oldFile?: SourceFile): void {
if (!this.newFileChanges) {
this.newFileChanges = createMultiMap<string, NewFileInsertion>();
}
this.newFileChanges.add(fileName, { oldFile, statements });
}
public insertFirstParameter(sourceFile: SourceFile, parameters: NodeArray<ParameterDeclaration>, newParam: ParameterDeclaration): void {
const p0 = firstOrUndefined(parameters);
if (p0) {
this.insertNodeBefore(sourceFile, p0, newParam);
}
else {
this.insertNodeAt(sourceFile, parameters.pos, newParam);
}
}
public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false, options: ConfigurableStartEnd = {}): void {
this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNode, this.getOptionsForInsertNodeBefore(before, newNode, blankLineBetween));
}
public insertNodesBefore(sourceFile: SourceFile, before: Node, newNodes: readonly Node[], blankLineBetween = false, options: ConfigurableStartEnd = {}): void {
this.insertNodesAt(sourceFile, getAdjustedStartPosition(sourceFile, before, options), newNodes, this.getOptionsForInsertNodeBefore(before, first(newNodes), blankLineBetween));
}
public insertModifierAt(sourceFile: SourceFile, pos: number, modifier: SyntaxKind, options: InsertNodeOptions = {}): void {
this.insertNodeAt(sourceFile, pos, factory.createToken(modifier), options);
}
public insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void {
return this.insertModifierAt(sourceFile, before.getStart(sourceFile), modifier, { suffix: " " });
}
public insertCommentBeforeLine(sourceFile: SourceFile, lineNumber: number, position: number, commentText: string): void {
const lineStartPosition = getStartPositionOfLine(lineNumber, sourceFile);
const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition);
// First try to see if we can put the comment on the previous line.
// We need to make sure that we are not in the middle of a string literal or a comment.
// If so, we do not want to separate the node from its comment if we can.
// Otherwise, add an extra new line immediately before the error span.
const insertAtLineStart = isValidLocationToAddComment(sourceFile, startPosition);
const token = getTouchingToken(sourceFile, insertAtLineStart ? startPosition : position);
const indent = sourceFile.text.slice(lineStartPosition, startPosition);
const text = `${insertAtLineStart ? "" : this.newLineCharacter}//${commentText}${this.newLineCharacter}${indent}`;
this.insertText(sourceFile, token.getStart(sourceFile), text);
}
public insertJsdocCommentBefore(sourceFile: SourceFile, node: HasJSDoc, tag: JSDoc): void {
const fnStart = node.getStart(sourceFile);
if (node.jsDoc) {
for (const jsdoc of node.jsDoc) {
this.deleteRange(sourceFile, {
pos: getLineStartPositionForPosition(jsdoc.getStart(sourceFile), sourceFile),
end: getAdjustedEndPosition(sourceFile, jsdoc, /*options*/ {}),
});
}
}
const startPosition = getPrecedingNonSpaceCharacterPosition(sourceFile.text, fnStart - 1);
const indent = sourceFile.text.slice(startPosition, fnStart);
this.insertNodeAt(sourceFile, fnStart, tag, { suffix: this.newLineCharacter + indent });
}
private createJSDocText(sourceFile: SourceFile, node: HasJSDoc) {
const comments = flatMap(node.jsDoc, jsDoc => isString(jsDoc.comment) ? factory.createJSDocText(jsDoc.comment) : jsDoc.comment) as JSDocComment[];
const jsDoc = singleOrUndefined(node.jsDoc);
return jsDoc && positionsAreOnSameLine(jsDoc.pos, jsDoc.end, sourceFile) && length(comments) === 0 ? undefined :
factory.createNodeArray(intersperse(comments, factory.createJSDocText("\n")));
}
public replaceJSDocComment(sourceFile: SourceFile, node: HasJSDoc, tags: readonly JSDocTag[]): void {
this.insertJsdocCommentBefore(sourceFile, updateJSDocHost(node), factory.createJSDocComment(this.createJSDocText(sourceFile, node), factory.createNodeArray(tags)));
}
public addJSDocTags(sourceFile: SourceFile, parent: HasJSDoc, newTags: readonly JSDocTag[]): void {
const oldTags = flatMapToMutable(parent.jsDoc, j => j.tags);
const unmergedNewTags = newTags.filter(newTag =>
!oldTags.some((tag, i) => {
const merged = tryMergeJsdocTags(tag, newTag);
if (merged) oldTags[i] = merged;
return !!merged;
})
);
this.replaceJSDocComment(sourceFile, parent, [...oldTags, ...unmergedNewTags]);
}
public filterJSDocTags(sourceFile: SourceFile, parent: HasJSDoc, predicate: (tag: JSDocTag) => boolean): void {
this.replaceJSDocComment(sourceFile, parent, filter(flatMapToMutable(parent.jsDoc, j => j.tags), predicate));
}
public replaceRangeWithText(sourceFile: SourceFile, range: TextRange, text: string): void {
this.changes.push({ kind: ChangeKind.Text, sourceFile, range, text });
}
public insertText(sourceFile: SourceFile, pos: number, text: string): void {
this.replaceRangeWithText(sourceFile, createRange(pos), text);
}
/** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): boolean {
let endNode: Node | undefined;
if (isFunctionLike(node)) {
endNode = findChildOfKind(node, SyntaxKind.CloseParenToken, sourceFile);
if (!endNode) {
if (!isArrowFunction(node)) return false; // Function missing parentheses, give up
// If no `)`, is an arrow function `x => x`, so use the end of the first parameter
endNode = first(node.parameters);
}
}
else {
endNode = (node.kind === SyntaxKind.VariableDeclaration ? node.exclamationToken : node.questionToken) ?? node.name;
}
this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
return true;
}
public tryInsertThisTypeAnnotation(sourceFile: SourceFile, node: ThisTypeAnnotatable, type: TypeNode): void {
const start = findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile)!.getStart(sourceFile) + 1;
const suffix = node.parameters.length ? ", " : "";
this.insertNodeAt(sourceFile, start, type, { prefix: "this: ", suffix });
}
public insertTypeParameters(sourceFile: SourceFile, node: SignatureDeclaration, typeParameters: readonly TypeParameterDeclaration[]): void {
// If no `(`, is an arrow function `x => x`, so use the pos of the first parameter
const start = (findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile) || first(node.parameters)).getStart(sourceFile);
this.insertNodesAt(sourceFile, start, typeParameters, { prefix: "<", suffix: ">", joiner: ", " });
}
private getOptionsForInsertNodeBefore(before: Node, inserted: Node, blankLineBetween: boolean): InsertNodeOptions {
if (isStatement(before) || isClassElement(before)) {
return { suffix: blankLineBetween ? this.newLineCharacter + this.newLineCharacter : this.newLineCharacter };
}
else if (isVariableDeclaration(before)) { // insert `x = 1, ` into `const x = 1, y = 2;
return { suffix: ", " };
}
else if (isParameter(before)) {
return isParameter(inserted) ? { suffix: ", " } : {};
}
else if (isStringLiteral(before) && isImportDeclaration(before.parent) || isNamedImports(before)) {
return { suffix: ", " };
}
else if (isImportSpecifier(before)) {
return { suffix: "," + (blankLineBetween ? this.newLineCharacter : " ") };
}
return Debug.failBadSyntaxKind(before); // We haven't handled this kind of node yet -- add it
}
public insertNodeAtConstructorStart(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void {
const firstStatement = firstOrUndefined(ctr.body!.statements);
if (!firstStatement || !ctr.body!.multiLine) {
this.replaceConstructorBody(sourceFile, ctr, [newStatement, ...ctr.body!.statements]);
}
else {
this.insertNodeBefore(sourceFile, firstStatement, newStatement);
}
}
public insertNodeAtConstructorStartAfterSuperCall(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void {
const superCallStatement = find(ctr.body!.statements, stmt => isExpressionStatement(stmt) && isSuperCall(stmt.expression));
if (!superCallStatement || !ctr.body!.multiLine) {
this.replaceConstructorBody(sourceFile, ctr, [...ctr.body!.statements, newStatement]);
}
else {
this.insertNodeAfter(sourceFile, superCallStatement, newStatement);
}
}
public insertNodeAtConstructorEnd(sourceFile: SourceFile, ctr: ConstructorDeclaration, newStatement: Statement): void {
const lastStatement = lastOrUndefined(ctr.body!.statements);
if (!lastStatement || !ctr.body!.multiLine) {
this.replaceConstructorBody(sourceFile, ctr, [...ctr.body!.statements, newStatement]);
}
else {
this.insertNodeAfter(sourceFile, lastStatement, newStatement);
}
}
private replaceConstructorBody(sourceFile: SourceFile, ctr: ConstructorDeclaration, statements: readonly Statement[]): void {
this.replaceNode(sourceFile, ctr.body!, factory.createBlock(statements, /*multiLine*/ true));
}
public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void {
const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {});
this.insertNodeAt(sourceFile, pos, newNode, {
prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken()!.pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter,
suffix: this.newLineCharacter,
});
}
public insertMemberAtStart(sourceFile: SourceFile, node: ClassLikeDeclaration | InterfaceDeclaration | TypeLiteralNode | EnumDeclaration, newElement: ClassElement | PropertySignature | MethodSignature | EnumMember): void {
this.insertNodeAtStartWorker(sourceFile, node, newElement);
}
public insertNodeAtObjectStart(sourceFile: SourceFile, obj: ObjectLiteralExpression, newElement: ObjectLiteralElementLike): void {
this.insertNodeAtStartWorker(sourceFile, obj, newElement);
}
private insertNodeAtStartWorker(sourceFile: SourceFile, node: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression | TypeLiteralNode | EnumDeclaration, newElement: ClassElement | ObjectLiteralElementLike | PropertySignature | MethodSignature | EnumMember): void {
const indentation = this.guessIndentationFromExistingMembers(sourceFile, node) ?? this.computeIndentationForNewMember(sourceFile, node);
this.insertNodeAt(sourceFile, getMembersOrProperties(node).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, node, indentation));
}
/**
* Tries to guess the indentation from the existing members of a class/interface/object. All members must be on
* new lines and must share the same indentation.
*/
private guessIndentationFromExistingMembers(sourceFile: SourceFile, node: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression | TypeLiteralNode | EnumDeclaration) {
let indentation: number | undefined;
let lastRange: TextRange = node;
for (const member of getMembersOrProperties(node)) {
if (rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) {
// each indented member must be on a new line
return undefined;
}
const memberStart = member.getStart(sourceFile);
const memberIndentation = formatting.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options);
if (indentation === undefined) {
indentation = memberIndentation;
}
else if (memberIndentation !== indentation) {
// indentation of multiple members is not consistent
return undefined;
}
lastRange = member;
}
return indentation;
}
private computeIndentationForNewMember(sourceFile: SourceFile, node: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression | TypeLiteralNode | EnumDeclaration) {
const nodeStart = node.getStart(sourceFile);
return formatting.SmartIndenter.findFirstNonWhitespaceColumn(getLineStartPositionForPosition(nodeStart, sourceFile), nodeStart, sourceFile, this.formatContext.options)
+ (this.formatContext.options.indentSize ?? 4);
}
private getInsertNodeAtStartInsertOptions(sourceFile: SourceFile, node: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression | TypeLiteralNode | EnumDeclaration, indentation: number): InsertNodeOptions {
// Rules:
// - Always insert leading newline.
// - For object literals:
// - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file
// (because trailing commas are generally illegal in a JSON file).
// - Add a leading comma if the source file is not a JSON file, there are existing insertions,
// and the node is empty (because we didn't add a trailing comma per the previous rule).
// - Only insert a trailing newline if body is single-line and there are no other insertions for the node.
// NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`.
const members = getMembersOrProperties(node);
const isEmpty = members.length === 0;
const isFirstInsertion = !this.classesWithNodesInsertedAtStart.has(getNodeId(node));
if (isFirstInsertion) {
this.classesWithNodesInsertedAtStart.set(getNodeId(node), { node, sourceFile });
}
const insertTrailingComma = isObjectLiteralExpression(node) && (!isJsonSourceFile(sourceFile) || !isEmpty);
const insertLeadingComma = isObjectLiteralExpression(node) && isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion;
return {
indentation,
prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter,
suffix: insertTrailingComma ? "," : isInterfaceDeclaration(node) && isEmpty ? ";" : "",
};
}
public insertNodeAfterComma(sourceFile: SourceFile, after: Node, newNode: Node): void {
const endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode);
this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
}
public insertNodeAfter(sourceFile: SourceFile, after: Node, newNode: Node): void {
const endPosition = this.insertNodeAfterWorker(sourceFile, after, newNode);
this.insertNodeAt(sourceFile, endPosition, newNode, this.getInsertNodeAfterOptions(sourceFile, after));
}
public insertNodeAtEndOfList(sourceFile: SourceFile, list: NodeArray<Node>, newNode: Node): void {
this.insertNodeAt(sourceFile, list.end, newNode, { prefix: ", " });
}
public insertNodesAfter(sourceFile: SourceFile, after: Node, newNodes: readonly Node[]): void {
const endPosition = this.insertNodeAfterWorker(sourceFile, after, first(newNodes));
this.insertNodesAt(sourceFile, endPosition, newNodes, this.getInsertNodeAfterOptions(sourceFile, after));
}
private insertNodeAfterWorker(sourceFile: SourceFile, after: Node, newNode: Node): number {
if (needSemicolonBetween(after, newNode)) {
// check if previous statement ends with semicolon
// if not - insert semicolon to preserve the code from changing the meaning due to ASI
if (sourceFile.text.charCodeAt(after.end - 1) !== CharacterCodes.semicolon) {
this.replaceRange(sourceFile, createRange(after.end), factory.createToken(SyntaxKind.SemicolonToken));
}
}
const endPosition = getAdjustedEndPosition(sourceFile, after, {});
return endPosition;
}
private getInsertNodeAfterOptions(sourceFile: SourceFile, after: Node): InsertNodeOptions {
const options = this.getInsertNodeAfterOptionsWorker(after);
return {
...options,
prefix: after.end === sourceFile.end && isStatement(after) ? (options.prefix ? `\n${options.prefix}` : "\n") : options.prefix,
};
}
private getInsertNodeAfterOptionsWorker(node: Node): InsertNodeOptions {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ModuleDeclaration:
return { prefix: this.newLineCharacter, suffix: this.newLineCharacter };
case SyntaxKind.VariableDeclaration:
case SyntaxKind.StringLiteral:
case SyntaxKind.Identifier:
return { prefix: ", " };
case SyntaxKind.PropertyAssignment:
return { suffix: "," + this.newLineCharacter };
case SyntaxKind.ExportKeyword:
return { prefix: " " };
case SyntaxKind.Parameter:
return {};
default:
Debug.assert(isStatement(node) || isClassOrTypeElement(node)); // Else we haven't handled this kind of node yet -- add it
return { suffix: this.newLineCharacter };
}
}
public insertName(sourceFile: SourceFile, node: FunctionExpression | ClassExpression | ArrowFunction, name: string): void {
Debug.assert(!node.name);
if (node.kind === SyntaxKind.ArrowFunction) {
const arrow = findChildOfKind(node, SyntaxKind.EqualsGreaterThanToken, sourceFile)!;
const lparen = findChildOfKind(node, SyntaxKind.OpenParenToken, sourceFile);
if (lparen) {
// `() => {}` --> `function f() {}`
this.insertNodesAt(sourceFile, lparen.getStart(sourceFile), [factory.createToken(SyntaxKind.FunctionKeyword), factory.createIdentifier(name)], { joiner: " " });
deleteNode(this, sourceFile, arrow);
}
else {
// `x => {}` -> `function f(x) {}`
this.insertText(sourceFile, first(node.parameters).getStart(sourceFile), `function ${name}(`);
// Replacing full range of arrow to get rid of the leading space -- replace ` =>` with `)`
this.replaceRange(sourceFile, arrow, factory.createToken(SyntaxKind.CloseParenToken));
}