/
formatting.ts
1397 lines (1229 loc) · 68.1 KB
/
formatting.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
/* @internal */
namespace ts.formatting {
export interface FormatContext {
readonly options: FormatCodeSettings;
readonly getRules: RulesMap;
readonly host: FormattingHost;
}
export interface TextRangeWithKind<T extends SyntaxKind = SyntaxKind> extends TextRange {
kind: T;
}
export type TextRangeWithTriviaKind = TextRangeWithKind<TriviaSyntaxKind>;
export interface TokenInfo {
leadingTrivia: TextRangeWithTriviaKind[] | undefined;
token: TextRangeWithKind;
trailingTrivia: TextRangeWithTriviaKind[] | undefined;
}
export function createTextRangeWithKind<T extends SyntaxKind>(pos: number, end: number, kind: T): TextRangeWithKind<T> {
const textRangeWithKind: TextRangeWithKind<T> = { pos, end, kind };
if (Debug.isDebugging) {
Object.defineProperty(textRangeWithKind, "__debugKind", {
get: () => Debug.formatSyntaxKind(kind),
});
}
return textRangeWithKind;
}
const enum Constants {
Unknown = -1
}
/*
* Indentation for the scope that can be dynamically recomputed.
* i.e
* while(true)
* { let x;
* }
* Normally indentation is applied only to the first token in line so at glance 'let' should not be touched.
* However if some format rule adds new line between '}' and 'let' 'let' will become
* the first token in line so it should be indented
*/
interface DynamicIndentation {
getIndentationForToken(tokenLine: number, tokenKind: SyntaxKind, container: Node, suppressDelta: boolean): number;
getIndentationForComment(owningToken: SyntaxKind, tokenIndentation: number, container: Node): number;
/**
* Indentation for open and close tokens of the node if it is block or another node that needs special indentation
* ... {
* .........<child>
* ....}
* ____ - indentation
* ____ - delta
*/
getIndentation(): number;
/**
* Prefered relative indentation for child nodes.
* Delta is used to carry the indentation info
* foo(bar({
* $
* }))
* Both 'foo', 'bar' introduce new indentation with delta = 4, but total indentation in $ is not 8.
* foo: { indentation: 0, delta: 4 }
* bar: { indentation: foo.indentation + foo.delta = 4, delta: 4} however 'foo' and 'bar' are on the same line
* so bar inherits indentation from foo and bar.delta will be 4
*
*/
getDelta(child: TextRangeWithKind): number;
/**
* Formatter calls this function when rule adds or deletes new lines from the text
* so indentation scope can adjust values of indentation and delta.
*/
recomputeIndentation(lineAddedByFormatting: boolean, parent: Node): void;
}
export function formatOnEnter(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[] {
const line = sourceFile.getLineAndCharacterOfPosition(position).line;
if (line === 0) {
return [];
}
// After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
// If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
// trailing whitespaces. So the end of the formatting span should be the later one between:
// 1. the end of the previous line
// 2. the last non-whitespace character in the current line
let endOfFormatSpan = getEndLinePosition(line, sourceFile);
while (isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
// if the character at the end of the span is a line break, we shouldn't include it, because it indicates we don't want to
// touch the current line at all. Also, on some OSes the line break consists of two characters (\r\n), we should test if the
// previous character before the end of format span is line break character as well.
if (isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
const span = {
// get start position for the previous line
pos: getStartPositionOfLine(line - 1, sourceFile),
// end value is exclusive so add 1 to the result
end: endOfFormatSpan + 1
};
return formatSpan(span, sourceFile, formatContext, FormattingRequestKind.FormatOnEnter);
}
export function formatOnSemicolon(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[] {
const semicolon = findImmediatelyPrecedingTokenOfKind(position, SyntaxKind.SemicolonToken, sourceFile);
return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, FormattingRequestKind.FormatOnSemicolon);
}
export function formatOnOpeningCurly(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[] {
const openingCurly = findImmediatelyPrecedingTokenOfKind(position, SyntaxKind.OpenBraceToken, sourceFile);
if (!openingCurly) {
return [];
}
const curlyBraceRange = openingCurly.parent;
const outermostNode = findOutermostNodeWithinListLevel(curlyBraceRange);
/**
* We limit the span to end at the opening curly to handle the case where
* the brace matched to that just typed will be incorrect after further edits.
* For example, we could type the opening curly for the following method
* body without brace-matching activated:
* ```
* class C {
* foo()
* }
* ```
* and we wouldn't want to move the closing brace.
*/
const textRange: TextRange = {
pos: getLineStartPositionForPosition(outermostNode!.getStart(sourceFile), sourceFile), // TODO: GH#18217
end: position
};
return formatSpan(textRange, sourceFile, formatContext, FormattingRequestKind.FormatOnOpeningCurlyBrace);
}
export function formatOnClosingCurly(position: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[] {
const precedingToken = findImmediatelyPrecedingTokenOfKind(position, SyntaxKind.CloseBraceToken, sourceFile);
return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, FormattingRequestKind.FormatOnClosingCurlyBrace);
}
export function formatDocument(sourceFile: SourceFile, formatContext: FormatContext): TextChange[] {
const span = {
pos: 0,
end: sourceFile.text.length
};
return formatSpan(span, sourceFile, formatContext, FormattingRequestKind.FormatDocument);
}
export function formatSelection(start: number, end: number, sourceFile: SourceFile, formatContext: FormatContext): TextChange[] {
// format from the beginning of the line
const span = {
pos: getLineStartPositionForPosition(start, sourceFile),
end,
};
return formatSpan(span, sourceFile, formatContext, FormattingRequestKind.FormatSelection);
}
/**
* Validating `expectedTokenKind` ensures the token was typed in the context we expect (eg: not a comment).
* @param expectedTokenKind The kind of the last token constituting the desired parent node.
*/
function findImmediatelyPrecedingTokenOfKind(end: number, expectedTokenKind: SyntaxKind, sourceFile: SourceFile): Node | undefined {
const precedingToken = findPrecedingToken(end, sourceFile);
return precedingToken && precedingToken.kind === expectedTokenKind && end === precedingToken.getEnd() ?
precedingToken :
undefined;
}
/**
* Finds the highest node enclosing `node` at the same list level as `node`
* and whose end does not exceed `node.end`.
*
* Consider typing the following
* ```
* let x = 1;
* while (true) {
* }
* ```
* Upon typing the closing curly, we want to format the entire `while`-statement, but not the preceding
* variable declaration.
*/
function findOutermostNodeWithinListLevel(node: Node | undefined) {
let current = node;
while (current &&
current.parent &&
current.parent.end === node!.end &&
!isListElement(current.parent, current)) {
current = current.parent;
}
return current;
}
// Returns true if node is a element in some list in parent
// i.e. parent is class declaration with the list of members and node is one of members.
function isListElement(parent: Node, node: Node): boolean {
switch (parent.kind) {
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
return rangeContainsRange((parent as InterfaceDeclaration).members, node);
case SyntaxKind.ModuleDeclaration:
const body = (parent as ModuleDeclaration).body;
return !!body && body.kind === SyntaxKind.ModuleBlock && rangeContainsRange(body.statements, node);
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
case SyntaxKind.ModuleBlock:
return rangeContainsRange((parent as Block).statements, node);
case SyntaxKind.CatchClause:
return rangeContainsRange((parent as CatchClause).block.statements, node);
}
return false;
}
/** find node that fully contains given text range */
function findEnclosingNode(range: TextRange, sourceFile: SourceFile): Node {
return find(sourceFile);
function find(n: Node): Node {
const candidate = forEachChild(n, c => startEndContainsRange(c.getStart(sourceFile), c.end, range) && c);
if (candidate) {
const result = find(candidate);
if (result) {
return result;
}
}
return n;
}
}
/** formatting is not applied to ranges that contain parse errors.
* This function will return a predicate that for a given text range will tell
* if there are any parse errors that overlap with the range.
*/
function prepareRangeContainsErrorFunction(errors: readonly Diagnostic[], originalRange: TextRange): (r: TextRange) => boolean {
if (!errors.length) {
return rangeHasNoErrors;
}
// pick only errors that fall in range
const sorted = errors
.filter(d => rangeOverlapsWithStartEnd(originalRange, d.start!, d.start! + d.length!)) // TODO: GH#18217
.sort((e1, e2) => e1.start! - e2.start!);
if (!sorted.length) {
return rangeHasNoErrors;
}
let index = 0;
return r => {
// in current implementation sequence of arguments [r1, r2...] is monotonically increasing.
// 'index' tracks the index of the most recent error that was checked.
while (true) {
if (index >= sorted.length) {
// all errors in the range were already checked -> no error in specified range
return false;
}
const error = sorted[index];
if (r.end <= error.start!) {
// specified range ends before the error referred by 'index' - no error in range
return false;
}
if (startEndOverlapsWithStartEnd(r.pos, r.end, error.start!, error.start! + error.length!)) {
// specified range overlaps with error range
return true;
}
index++;
}
};
function rangeHasNoErrors(): boolean {
return false;
}
}
/**
* Start of the original range might fall inside the comment - scanner will not yield appropriate results
* This function will look for token that is located before the start of target range
* and return its end as start position for the scanner.
*/
function getScanStartPosition(enclosingNode: Node, originalRange: TextRange, sourceFile: SourceFile): number {
const start = enclosingNode.getStart(sourceFile);
if (start === originalRange.pos && enclosingNode.end === originalRange.end) {
return start;
}
const precedingToken = findPrecedingToken(originalRange.pos, sourceFile);
if (!precedingToken) {
// no preceding token found - start from the beginning of enclosing node
return enclosingNode.pos;
}
// preceding token ends after the start of original range (i.e when originalRange.pos falls in the middle of literal)
// start from the beginning of enclosingNode to handle the entire 'originalRange'
if (precedingToken.end >= originalRange.pos) {
return enclosingNode.pos;
}
return precedingToken.end;
}
/*
* For cases like
* if (a ||
* b ||$
* c) {...}
* If we hit Enter at $ we want line ' b ||' to be indented.
* Formatting will be applied to the last two lines.
* Node that fully encloses these lines is binary expression 'a ||...'.
* Initial indentation for this node will be 0.
* Binary expressions don't introduce new indentation scopes, however it is possible
* that some parent node on the same line does - like if statement in this case.
* Note that we are considering parents only from the same line with initial node -
* if parent is on the different line - its delta was already contributed
* to the initial indentation.
*/
function getOwnOrInheritedDelta(n: Node, options: FormatCodeSettings, sourceFile: SourceFile): number {
let previousLine = Constants.Unknown;
let child: Node | undefined;
while (n) {
const line = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)).line;
if (previousLine !== Constants.Unknown && line !== previousLine) {
break;
}
if (SmartIndenter.shouldIndentChildNode(options, n, child, sourceFile)) {
return options.indentSize!;
}
previousLine = line;
child = n;
n = n.parent;
}
return 0;
}
export function formatNodeGivenIndentation(node: Node, sourceFileLike: SourceFileLike, languageVariant: LanguageVariant, initialIndentation: number, delta: number, formatContext: FormatContext): TextChange[] {
const range = { pos: node.pos, end: node.end };
return getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner => formatSpanWorker(
range,
node,
initialIndentation,
delta,
scanner,
formatContext,
FormattingRequestKind.FormatSelection,
_ => false, // assume that node does not have any errors
sourceFileLike));
}
function formatNodeLines(node: Node | undefined, sourceFile: SourceFile, formatContext: FormatContext, requestKind: FormattingRequestKind): TextChange[] {
if (!node) {
return [];
}
const span = {
pos: getLineStartPositionForPosition(node.getStart(sourceFile), sourceFile),
end: node.end
};
return formatSpan(span, sourceFile, formatContext, requestKind);
}
function formatSpan(originalRange: TextRange, sourceFile: SourceFile, formatContext: FormatContext, requestKind: FormattingRequestKind): TextChange[] {
// find the smallest node that fully wraps the range and compute the initial indentation for the node
const enclosingNode = findEnclosingNode(originalRange, sourceFile);
return getFormattingScanner(
sourceFile.text,
sourceFile.languageVariant,
getScanStartPosition(enclosingNode, originalRange, sourceFile),
originalRange.end,
scanner => formatSpanWorker(
originalRange,
enclosingNode,
SmartIndenter.getIndentationForNode(enclosingNode, originalRange, sourceFile, formatContext.options),
getOwnOrInheritedDelta(enclosingNode, formatContext.options, sourceFile),
scanner,
formatContext,
requestKind,
prepareRangeContainsErrorFunction(sourceFile.parseDiagnostics, originalRange),
sourceFile));
}
function formatSpanWorker(
originalRange: TextRange,
enclosingNode: Node,
initialIndentation: number,
delta: number,
formattingScanner: FormattingScanner,
{ options, getRules, host }: FormatContext,
requestKind: FormattingRequestKind,
rangeContainsError: (r: TextRange) => boolean,
sourceFile: SourceFileLike): TextChange[] {
// formatting context is used by rules provider
const formattingContext = new FormattingContext(sourceFile, requestKind, options);
let previousRange: TextRangeWithKind;
let previousParent: Node;
let previousRangeStartLine: number;
let lastIndentedLine: number;
let indentationOnLastIndentedLine = Constants.Unknown;
const edits: TextChange[] = [];
formattingScanner.advance();
if (formattingScanner.isOnToken()) {
const startLine = sourceFile.getLineAndCharacterOfPosition(enclosingNode.getStart(sourceFile)).line;
let undecoratedStartLine = startLine;
if (enclosingNode.decorators) {
undecoratedStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(enclosingNode, sourceFile)).line;
}
processNode(enclosingNode, enclosingNode, startLine, undecoratedStartLine, initialIndentation, delta);
}
if (!formattingScanner.isOnToken()) {
const indentation = SmartIndenter.nodeWillIndentChild(options, enclosingNode, /*child*/ undefined, sourceFile, /*indentByDefault*/ false)
? initialIndentation + options.indentSize!
: initialIndentation;
const leadingTrivia = formattingScanner.getCurrentLeadingTrivia();
if (leadingTrivia) {
indentTriviaItems(leadingTrivia, indentation, /*indentNextTokenOrTrivia*/ false,
item => processRange(item, sourceFile.getLineAndCharacterOfPosition(item.pos), enclosingNode, enclosingNode, /*dynamicIndentation*/ undefined!));
if (options.trimTrailingWhitespace !== false) {
trimTrailingWhitespacesForRemainingRange(leadingTrivia);
}
}
}
if (previousRange! && formattingScanner.getStartPos() >= originalRange.end) {
const tokenInfo =
formattingScanner.isOnEOF() ? formattingScanner.readEOFTokenRange() :
formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(enclosingNode).token :
undefined;
if (tokenInfo) {
const parent = findPrecedingToken(tokenInfo.end, sourceFile, enclosingNode)?.parent || previousParent!;
processPair(
tokenInfo,
sourceFile.getLineAndCharacterOfPosition(tokenInfo.pos).line,
parent,
previousRange,
previousRangeStartLine!,
previousParent!,
parent,
/*dynamicIndentation*/ undefined);
}
}
return edits;
// local functions
/** Tries to compute the indentation for a list element.
* If list element is not in range then
* function will pick its actual indentation
* so it can be pushed downstream as inherited indentation.
* If list element is in the range - its indentation will be equal
* to inherited indentation from its predecessors.
*/
function tryComputeIndentationForListItem(startPos: number,
endPos: number,
parentStartLine: number,
range: TextRange,
inheritedIndentation: number): number {
if (rangeOverlapsWithStartEnd(range, startPos, endPos) ||
rangeContainsStartEnd(range, startPos, endPos) /* Not to miss zero-range nodes e.g. JsxText */) {
if (inheritedIndentation !== Constants.Unknown) {
return inheritedIndentation;
}
}
else {
const startLine = sourceFile.getLineAndCharacterOfPosition(startPos).line;
const startLinePosition = getLineStartPositionForPosition(startPos, sourceFile);
const column = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, startPos, sourceFile, options);
if (startLine !== parentStartLine || startPos === column) {
// Use the base indent size if it is greater than
// the indentation of the inherited predecessor.
const baseIndentSize = SmartIndenter.getBaseIndentation(options);
return baseIndentSize > column ? baseIndentSize : column;
}
}
return Constants.Unknown;
}
function computeIndentation(
node: TextRangeWithKind,
startLine: number,
inheritedIndentation: number,
parent: Node,
parentDynamicIndentation: DynamicIndentation,
effectiveParentStartLine: number
): { indentation: number, delta: number; } {
const delta = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize! : 0;
if (effectiveParentStartLine === startLine) {
// if node is located on the same line with the parent
// - inherit indentation from the parent
// - push children if either parent of node itself has non-zero delta
return {
indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(),
delta: Math.min(options.indentSize!, parentDynamicIndentation.getDelta(node) + delta)
};
}
else if (inheritedIndentation === Constants.Unknown) {
if (node.kind === SyntaxKind.OpenParenToken && startLine === lastIndentedLine) {
// the is used for chaining methods formatting
// - we need to get the indentation on last line and the delta of parent
return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) };
}
else if (
SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile) ||
SmartIndenter.childIsUnindentedBranchOfConditionalExpression(parent, node, startLine, sourceFile) ||
SmartIndenter.argumentStartsOnSameLineAsPreviousArgument(parent, node, startLine, sourceFile)
) {
return { indentation: parentDynamicIndentation.getIndentation(), delta };
}
else {
return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta };
}
}
else {
return { indentation: inheritedIndentation, delta };
}
}
function getFirstNonDecoratorTokenOfNode(node: Node) {
if (node.modifiers && node.modifiers.length) {
return node.modifiers[0].kind;
}
switch (node.kind) {
case SyntaxKind.ClassDeclaration: return SyntaxKind.ClassKeyword;
case SyntaxKind.InterfaceDeclaration: return SyntaxKind.InterfaceKeyword;
case SyntaxKind.FunctionDeclaration: return SyntaxKind.FunctionKeyword;
case SyntaxKind.EnumDeclaration: return SyntaxKind.EnumDeclaration;
case SyntaxKind.GetAccessor: return SyntaxKind.GetKeyword;
case SyntaxKind.SetAccessor: return SyntaxKind.SetKeyword;
case SyntaxKind.MethodDeclaration:
if ((node as MethodDeclaration).asteriskToken) {
return SyntaxKind.AsteriskToken;
}
// falls through
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.Parameter:
const name = getNameOfDeclaration(node as Declaration);
if (name) {
return name.kind;
}
}
}
function getDynamicIndentation(node: Node, nodeStartLine: number, indentation: number, delta: number): DynamicIndentation {
return {
getIndentationForComment: (kind, tokenIndentation, container) => {
switch (kind) {
// preceding comment to the token that closes the indentation scope inherits the indentation from the scope
// .. {
// // comment
// }
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.CloseParenToken:
return indentation + getDelta(container);
}
return tokenIndentation !== Constants.Unknown ? tokenIndentation : indentation;
},
// if list end token is LessThanToken '>' then its delta should be explicitly suppressed
// so that LessThanToken as a binary operator can still be indented.
// foo.then
// <
// number,
// string,
// >();
// vs
// var a = xValue
// > yValue;
getIndentationForToken: (line, kind, container, suppressDelta) =>
!suppressDelta && shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation,
getIndentation: () => indentation,
getDelta,
recomputeIndentation: (lineAdded, parent) => {
if (SmartIndenter.shouldIndentChildNode(options, parent, node, sourceFile)) {
indentation += lineAdded ? options.indentSize! : -options.indentSize!;
delta = SmartIndenter.shouldIndentChildNode(options, node) ? options.indentSize! : 0;
}
}
};
function shouldAddDelta(line: number, kind: SyntaxKind, container: Node): boolean {
switch (kind) {
// open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent
case SyntaxKind.OpenBraceToken:
case SyntaxKind.CloseBraceToken:
case SyntaxKind.CloseParenToken:
case SyntaxKind.ElseKeyword:
case SyntaxKind.WhileKeyword:
case SyntaxKind.AtToken:
return false;
case SyntaxKind.SlashToken:
case SyntaxKind.GreaterThanToken:
switch (container.kind) {
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.JsxClosingElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.ExpressionWithTypeArguments:
return false;
}
break;
case SyntaxKind.OpenBracketToken:
case SyntaxKind.CloseBracketToken:
if (container.kind !== SyntaxKind.MappedType) {
return false;
}
break;
}
// if token line equals to the line of containing node (this is a first token in the node) - use node indentation
return nodeStartLine !== line
// if this token is the first token following the list of decorators, we do not need to indent
&& !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node));
}
function getDelta(child: TextRangeWithKind) {
// Delta value should be zero when the node explicitly prevents indentation of the child node
return SmartIndenter.nodeWillIndentChild(options, node, child, sourceFile, /*indentByDefault*/ true) ? delta : 0;
}
}
function processNode(node: Node, contextNode: Node, nodeStartLine: number, undecoratedNodeStartLine: number, indentation: number, delta: number) {
if (!rangeOverlapsWithStartEnd(originalRange, node.getStart(sourceFile), node.getEnd())) {
return;
}
const nodeDynamicIndentation = getDynamicIndentation(node, nodeStartLine, indentation, delta);
// a useful observations when tracking context node
// /
// [a]
// / | \
// [b] [c] [d]
// node 'a' is a context node for nodes 'b', 'c', 'd'
// except for the leftmost leaf token in [b] - in this case context node ('e') is located somewhere above 'a'
// this rule can be applied recursively to child nodes of 'a'.
//
// context node is set to parent node value after processing every child node
// context node is set to parent of the token after processing every token
let childContextNode = contextNode;
// if there are any tokens that logically belong to node and interleave child nodes
// such tokens will be consumed in processChildNode for the child that follows them
forEachChild(
node,
child => {
processChildNode(child, /*inheritedIndentation*/ Constants.Unknown, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false);
},
nodes => {
processChildNodes(nodes, node, nodeStartLine, nodeDynamicIndentation);
});
// proceed any tokens in the node that are located after child nodes
while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) {
const tokenInfo = formattingScanner.readTokenInfo(node);
if (tokenInfo.token.end > Math.min(node.end, originalRange.end)) {
break;
}
consumeTokenAndAdvanceScanner(tokenInfo, node, nodeDynamicIndentation, node);
}
function processChildNode(
child: Node,
inheritedIndentation: number,
parent: Node,
parentDynamicIndentation: DynamicIndentation,
parentStartLine: number,
undecoratedParentStartLine: number,
isListItem: boolean,
isFirstListItem?: boolean): number {
const childStartPos = child.getStart(sourceFile);
const childStartLine = sourceFile.getLineAndCharacterOfPosition(childStartPos).line;
let undecoratedChildStartLine = childStartLine;
if (child.decorators) {
undecoratedChildStartLine = sourceFile.getLineAndCharacterOfPosition(getNonDecoratorTokenPosOfNode(child, sourceFile)).line;
}
// if child is a list item - try to get its indentation, only if parent is within the original range.
let childIndentationAmount = Constants.Unknown;
if (isListItem && rangeContainsRange(originalRange, parent)) {
childIndentationAmount = tryComputeIndentationForListItem(childStartPos, child.end, parentStartLine, originalRange, inheritedIndentation);
if (childIndentationAmount !== Constants.Unknown) {
inheritedIndentation = childIndentationAmount;
}
}
// child node is outside the target range - do not dive inside
if (!rangeOverlapsWithStartEnd(originalRange, child.pos, child.end)) {
if (child.end < originalRange.pos) {
formattingScanner.skipToEndOf(child);
}
return inheritedIndentation;
}
if (child.getFullWidth() === 0) {
return inheritedIndentation;
}
while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) {
// proceed any parent tokens that are located prior to child.getStart()
const tokenInfo = formattingScanner.readTokenInfo(node);
if (tokenInfo.token.end > originalRange.end) {
return inheritedIndentation;
}
if (tokenInfo.token.end > childStartPos) {
if (tokenInfo.token.pos > childStartPos) {
formattingScanner.skipToStartOf(child);
}
// stop when formatting scanner advances past the beginning of the child
break;
}
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, node);
}
if (!formattingScanner.isOnToken() || formattingScanner.getStartPos() >= originalRange.end) {
return inheritedIndentation;
}
if (isToken(child)) {
// if child node is a token, it does not impact indentation, proceed it using parent indentation scope rules
const tokenInfo = formattingScanner.readTokenInfo(child);
// JSX text shouldn't affect indenting
if (child.kind !== SyntaxKind.JsxText) {
Debug.assert(tokenInfo.token.end === child.end, "Token end is child end");
consumeTokenAndAdvanceScanner(tokenInfo, node, parentDynamicIndentation, child);
return inheritedIndentation;
}
}
const effectiveParentStartLine = child.kind === SyntaxKind.Decorator ? childStartLine : undecoratedParentStartLine;
const childIndentation = computeIndentation(child, childStartLine, childIndentationAmount, node, parentDynamicIndentation, effectiveParentStartLine);
processNode(child, childContextNode, childStartLine, undecoratedChildStartLine, childIndentation.indentation, childIndentation.delta);
childContextNode = node;
if (isFirstListItem && parent.kind === SyntaxKind.ArrayLiteralExpression && inheritedIndentation === Constants.Unknown) {
inheritedIndentation = childIndentation.indentation;
}
return inheritedIndentation;
}
function processChildNodes(nodes: NodeArray<Node>,
parent: Node,
parentStartLine: number,
parentDynamicIndentation: DynamicIndentation): void {
Debug.assert(isNodeArray(nodes));
const listStartToken = getOpenTokenForList(parent, nodes);
let listDynamicIndentation = parentDynamicIndentation;
let startLine = parentStartLine;
if (listStartToken !== SyntaxKind.Unknown) {
// introduce a new indentation scope for lists (including list start and end tokens)
while (formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) {
const tokenInfo = formattingScanner.readTokenInfo(parent);
if (tokenInfo.token.end > nodes.pos) {
// stop when formatting scanner moves past the beginning of node list
break;
}
else if (tokenInfo.token.kind === listStartToken) {
// consume list start token
startLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
let indentationOnListStartToken: number;
if (indentationOnLastIndentedLine !== Constants.Unknown) {
// scanner just processed list start token so consider last indentation as list indentation
// function foo(): { // last indentation was 0, list item will be indented based on this value
// foo: number;
// }: {};
indentationOnListStartToken = indentationOnLastIndentedLine;
}
else {
const startLinePosition = getLineStartPositionForPosition(tokenInfo.token.pos, sourceFile);
indentationOnListStartToken = SmartIndenter.findFirstNonWhitespaceColumn(startLinePosition, tokenInfo.token.pos, sourceFile, options);
}
listDynamicIndentation = getDynamicIndentation(parent, parentStartLine, indentationOnListStartToken, options.indentSize!); // TODO: GH#18217
}
else {
// consume any tokens that precede the list as child elements of 'node' using its indentation scope
consumeTokenAndAdvanceScanner(tokenInfo, parent, parentDynamicIndentation, parent);
}
}
}
let inheritedIndentation = Constants.Unknown;
for (let i = 0; i < nodes.length; i++) {
const child = nodes[i];
inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListItem*/ true, /*isFirstListItem*/ i === 0);
}
const listEndToken = getCloseTokenForOpenToken(listStartToken);
if (listEndToken !== SyntaxKind.Unknown && formattingScanner.isOnToken() && formattingScanner.getStartPos() < originalRange.end) {
let tokenInfo: TokenInfo | undefined = formattingScanner.readTokenInfo(parent);
if (tokenInfo.token.kind === SyntaxKind.CommaToken && isCallLikeExpression(parent)) {
const commaTokenLine = sourceFile.getLineAndCharacterOfPosition(tokenInfo.token.pos).line;
if (startLine !== commaTokenLine) {
formattingScanner.advance();
tokenInfo = formattingScanner.isOnToken() ? formattingScanner.readTokenInfo(parent) : undefined;
}
}
// consume the list end token only if it is still belong to the parent
// there might be the case when current token matches end token but does not considered as one
// function (x: function) <--
// without this check close paren will be interpreted as list end token for function expression which is wrong
if (tokenInfo && tokenInfo.token.kind === listEndToken && rangeContainsRange(parent, tokenInfo.token)) {
// consume list end token
consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation, parent, /*isListEndToken*/ true);
}
}
}
function consumeTokenAndAdvanceScanner(currentTokenInfo: TokenInfo, parent: Node, dynamicIndentation: DynamicIndentation, container: Node, isListEndToken?: boolean): void {
Debug.assert(rangeContainsRange(parent, currentTokenInfo.token));
const lastTriviaWasNewLine = formattingScanner.lastTrailingTriviaWasNewLine();
let indentToken = false;
if (currentTokenInfo.leadingTrivia) {
processTrivia(currentTokenInfo.leadingTrivia, parent, childContextNode, dynamicIndentation);
}
let lineAction = LineAction.None;
const isTokenInRange = rangeContainsRange(originalRange, currentTokenInfo.token);
const tokenStart = sourceFile.getLineAndCharacterOfPosition(currentTokenInfo.token.pos);
if (isTokenInRange) {
const rangeHasError = rangeContainsError(currentTokenInfo.token);
// save previousRange since processRange will overwrite this value with current one
const savePreviousRange = previousRange;
lineAction = processRange(currentTokenInfo.token, tokenStart, parent, childContextNode, dynamicIndentation);
// do not indent comments\token if token range overlaps with some error
if (!rangeHasError) {
if (lineAction === LineAction.None) {
// indent token only if end line of previous range does not match start line of the token
const prevEndLine = savePreviousRange && sourceFile.getLineAndCharacterOfPosition(savePreviousRange.end).line;
indentToken = lastTriviaWasNewLine && tokenStart.line !== prevEndLine;
}
else {
indentToken = lineAction === LineAction.LineAdded;
}
}
}
if (currentTokenInfo.trailingTrivia) {
processTrivia(currentTokenInfo.trailingTrivia, parent, childContextNode, dynamicIndentation);
}
if (indentToken) {
const tokenIndentation = (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) ?
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container, !!isListEndToken) :
Constants.Unknown;
let indentNextTokenOrTrivia = true;
if (currentTokenInfo.leadingTrivia) {
const commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
indentNextTokenOrTrivia = indentTriviaItems(currentTokenInfo.leadingTrivia, commentIndentation, indentNextTokenOrTrivia,
item => insertIndentation(item.pos, commentIndentation, /*lineAdded*/ false));
}
// indent token only if is it is in target range and does not overlap with any error ranges
if (tokenIndentation !== Constants.Unknown && indentNextTokenOrTrivia) {
insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAction === LineAction.LineAdded);
lastIndentedLine = tokenStart.line;
indentationOnLastIndentedLine = tokenIndentation;
}
}
formattingScanner.advance();
childContextNode = parent;
}
}
function indentTriviaItems(
trivia: TextRangeWithKind[],
commentIndentation: number,
indentNextTokenOrTrivia: boolean,
indentSingleLine: (item: TextRangeWithKind) => void) {
for (const triviaItem of trivia) {
const triviaInRange = rangeContainsRange(originalRange, triviaItem);
switch (triviaItem.kind) {
case SyntaxKind.MultiLineCommentTrivia:
if (triviaInRange) {
indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
}
indentNextTokenOrTrivia = false;
break;
case SyntaxKind.SingleLineCommentTrivia:
if (indentNextTokenOrTrivia && triviaInRange) {
indentSingleLine(triviaItem);
}
indentNextTokenOrTrivia = false;
break;
case SyntaxKind.NewLineTrivia:
indentNextTokenOrTrivia = true;
break;
}
}
return indentNextTokenOrTrivia;
}
function processTrivia(trivia: TextRangeWithKind[], parent: Node, contextNode: Node, dynamicIndentation: DynamicIndentation): void {
for (const triviaItem of trivia) {
if (isComment(triviaItem.kind) && rangeContainsRange(originalRange, triviaItem)) {
const triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos);
processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation);
}
}
}
function processRange(range: TextRangeWithKind,
rangeStart: LineAndCharacter,
parent: Node,
contextNode: Node,
dynamicIndentation: DynamicIndentation): LineAction {
const rangeHasError = rangeContainsError(range);
let lineAction = LineAction.None;
if (!rangeHasError) {
if (!previousRange) {
// trim whitespaces starting from the beginning of the span up to the current line
const originalStart = sourceFile.getLineAndCharacterOfPosition(originalRange.pos);
trimTrailingWhitespacesForLines(originalStart.line, rangeStart.line);
}
else {
lineAction =
processPair(range, rangeStart.line, parent, previousRange, previousRangeStartLine, previousParent, contextNode, dynamicIndentation);
}
}
previousRange = range;
previousParent = parent;
previousRangeStartLine = rangeStart.line;
return lineAction;
}
function processPair(currentItem: TextRangeWithKind,
currentStartLine: number,
currentParent: Node,
previousItem: TextRangeWithKind,
previousStartLine: number,
previousParent: Node,
contextNode: Node,
dynamicIndentation: DynamicIndentation | undefined): LineAction {
formattingContext.updateContext(previousItem, previousParent, currentItem, currentParent, contextNode);
const rules = getRules(formattingContext);
let trimTrailingWhitespaces = formattingContext.options.trimTrailingWhitespace !== false;
let lineAction = LineAction.None;
if (rules) {
// Apply rules in reverse order so that higher priority rules (which are first in the array)
// win in a conflict with lower priority rules.
forEachRight(rules, rule => {
lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine);
if (dynamicIndentation) {
switch (lineAction) {
case LineAction.LineRemoved:
// Handle the case where the next line is moved to be the end of this line.
// In this case we don't indent the next line in the next pass.
if (currentParent.getStart(sourceFile) === currentItem.pos) {
dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false, contextNode);
}