-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathTokenStreamCreator.swift
4540 lines (3968 loc) · 188 KB
/
TokenStreamCreator.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import SwiftOperators
import SwiftSyntax
fileprivate extension AccessorBlockSyntax {
/// Assuming that the accessor only contains an implicit getter (i.e. no
/// `get` or `set`), return the code block items in that getter.
var getterCodeBlockItems: CodeBlockItemListSyntax {
guard case .getter(let codeBlockItemList) = self.accessors else {
preconditionFailure("AccessorBlock has an accessor list and not just a getter")
}
return codeBlockItemList
}
}
/// Visits the nodes of a syntax tree and constructs a linear stream of formatting tokens that
/// tell the pretty printer how the source text should be laid out.
fileprivate final class TokenStreamCreator: SyntaxVisitor {
private var tokens = [Token]()
private var beforeMap = [TokenSyntax: [Token]]()
private var afterMap = [TokenSyntax: [[Token]]]()
private let config: Configuration
private let operatorTable: OperatorTable
private let maxlinelength: Int
private let selection: Selection
/// The index of the most recently appended break, or nil when no break has been appended.
private var lastBreakIndex: Int? = nil
/// Whether newlines can be merged into the most recent break, based on which tokens have been
/// appended since that break.
private var canMergeNewlinesIntoLastBreak = false
/// Keeps track of the kind of break that should be used inside a multiline string. This differs
/// depending on surrounding context due to some tricky special cases, so this lets us pass that
/// information down to the strings that need it.
private var pendingMultilineStringBreakKinds = [StringLiteralExprSyntax: BreakKind]()
/// Lists tokens that shouldn't be appended to the token stream as `syntax` tokens. They will be
/// printed conditionally using a different type of token.
private var ignoredTokens = Set<TokenSyntax>()
/// Lists the expressions that have been visited, from the outermost expression, where contextual
/// breaks and start/end contextual breaking tokens have been inserted.
private var preVisitedExprs = Set<SyntaxIdentifier>()
/// Tracks the "root" exprs where previsiting for contextual breaks started so that
/// `preVisitedExprs` can be emptied after exiting an expr tree.
private var rootExprs = Set<SyntaxIdentifier>()
/// Lists the tokens that are the closing or final delimiter of a node that shouldn't be split
/// from the preceding token. When breaks are inserted around compound expressions, the breaks are
/// moved past these tokens.
private var closingDelimiterTokens = Set<TokenSyntax>()
/// Tracks closures that are never allowed to be laid out entirely on one line (e.g., closures
/// in a function call containing multiple trailing closures).
private var forcedBreakingClosures = Set<SyntaxIdentifier>()
/// Tracks whether we last considered ourselves inside the selection
private var isInsideSelection = true
init(configuration: Configuration, selection: Selection, operatorTable: OperatorTable) {
self.config = configuration
self.selection = selection
self.operatorTable = operatorTable
self.maxlinelength = config.lineLength
super.init(viewMode: .all)
}
func makeStream(from node: Syntax) -> [Token] {
// if we have a selection, then we start outside of it
if case .ranges = selection {
appendToken(.disableFormatting(AbsolutePosition(utf8Offset: 0)))
isInsideSelection = false
}
// Because `walk` takes an `inout` argument, and we're a class, we have to do the following
// dance to pass ourselves in.
self.walk(node)
// Make sure we output any trailing text after the last selection range
if case .ranges = selection {
appendToken(.enableFormatting(nil))
}
defer { tokens = [] }
return tokens
}
var openings = 0
/// If the syntax token is non-nil, enqueue the given list of formatting tokens before it in the
/// token stream.
func before(_ token: TokenSyntax?, tokens: Token...) {
before(token, tokens: tokens)
}
/// If the syntax token is non-nil, enqueue the given list of formatting tokens before it in the
/// token stream.
func before(_ token: TokenSyntax?, tokens: [Token]) {
guard let tok = token else { return }
beforeMap[tok, default: []] += tokens
}
/// If the syntax token is non-nil, enqueue the given list of formatting tokens after it in the
/// token stream.
func after(_ token: TokenSyntax?, tokens: Token...) {
after(token, tokens: tokens)
}
/// If the syntax token is non-nil, enqueue the given list of formatting tokens after it in the
/// token stream.
func after(_ token: TokenSyntax?, tokens: [Token]) {
guard let tok = token else { return }
afterMap[tok, default: []].append(tokens)
}
/// Enqueues the given list of formatting tokens between each element of the given syntax
/// collection (but not before the first one nor after the last one).
private func insertTokens<Node: SyntaxCollection>(
_ tokens: Token...,
betweenElementsOf collectionNode: Node
) where Node.Element == Syntax {
for element in collectionNode.dropLast() {
after(element.lastToken(viewMode: .sourceAccurate), tokens: tokens)
}
}
/// Enqueues the given list of formatting tokens between each element of the given syntax
/// collection (but not before the first one nor after the last one).
private func insertTokens<Node: SyntaxCollection>(
_ tokens: Token...,
betweenElementsOf collectionNode: Node
) where Node.Element: SyntaxProtocol {
for element in collectionNode.dropLast() {
after(element.lastToken(viewMode: .sourceAccurate), tokens: tokens)
}
}
/// Enqueues the given list of formatting tokens between each element of the given syntax
/// collection (but not before the first one nor after the last one).
private func insertTokens<Node: SyntaxCollection>(
_ tokens: Token...,
betweenElementsOf collectionNode: Node
) where Node.Element == DeclSyntax {
for element in collectionNode.dropLast() {
after(element.lastToken(viewMode: .sourceAccurate), tokens: tokens)
}
}
private func verbatimToken(_ node: Syntax, indentingBehavior: IndentingBehavior = .allLines) {
if let firstToken = node.firstToken(viewMode: .sourceAccurate) {
appendBeforeTokens(firstToken)
}
appendToken(.verbatim(Verbatim(text: node.description, indentingBehavior: indentingBehavior)))
if let lastToken = node.lastToken(viewMode: .sourceAccurate) {
// Extract any comments that trail the verbatim block since they belong to the next syntax
// token. Leading comments don't need special handling since they belong to the current node,
// and will get printed.
appendAfterTokensAndTrailingComments(lastToken)
}
}
// MARK: - Type declaration nodes
override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeTypeDeclBlock(
Syntax(node),
attributes: node.attributes,
modifiers: node.modifiers,
typeKeyword: node.classKeyword,
identifier: node.name,
genericParameterOrPrimaryAssociatedTypeClause: node.genericParameterClause.map(Syntax.init),
inheritanceClause: node.inheritanceClause,
genericWhereClause: node.genericWhereClause,
memberBlock: node.memberBlock
)
return .visitChildren
}
override func visit(_ node: ActorDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeTypeDeclBlock(
Syntax(node),
attributes: node.attributes,
modifiers: node.modifiers,
typeKeyword: node.actorKeyword,
identifier: node.name,
genericParameterOrPrimaryAssociatedTypeClause: node.genericParameterClause.map(Syntax.init),
inheritanceClause: node.inheritanceClause,
genericWhereClause: node.genericWhereClause,
memberBlock: node.memberBlock
)
return .visitChildren
}
override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeTypeDeclBlock(
Syntax(node),
attributes: node.attributes,
modifiers: node.modifiers,
typeKeyword: node.structKeyword,
identifier: node.name,
genericParameterOrPrimaryAssociatedTypeClause: node.genericParameterClause.map(Syntax.init),
inheritanceClause: node.inheritanceClause,
genericWhereClause: node.genericWhereClause,
memberBlock: node.memberBlock
)
return .visitChildren
}
override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeTypeDeclBlock(
Syntax(node),
attributes: node.attributes,
modifiers: node.modifiers,
typeKeyword: node.enumKeyword,
identifier: node.name,
genericParameterOrPrimaryAssociatedTypeClause: node.genericParameterClause.map(Syntax.init),
inheritanceClause: node.inheritanceClause,
genericWhereClause: node.genericWhereClause,
memberBlock: node.memberBlock
)
return .visitChildren
}
override func visit(_ node: ProtocolDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeTypeDeclBlock(
Syntax(node),
attributes: node.attributes,
modifiers: node.modifiers,
typeKeyword: node.protocolKeyword,
identifier: node.name,
genericParameterOrPrimaryAssociatedTypeClause:
node.primaryAssociatedTypeClause.map(Syntax.init),
inheritanceClause: node.inheritanceClause,
genericWhereClause: node.genericWhereClause,
memberBlock: node.memberBlock
)
return .visitChildren
}
override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind {
guard let lastTokenOfExtendedType = node.extendedType.lastToken(viewMode: .sourceAccurate) else {
fatalError("ExtensionDeclSyntax.extendedType must have at least one token")
}
arrangeTypeDeclBlock(
Syntax(node),
attributes: node.attributes,
modifiers: node.modifiers,
typeKeyword: node.extensionKeyword,
identifier: lastTokenOfExtendedType,
genericParameterOrPrimaryAssociatedTypeClause: nil,
inheritanceClause: node.inheritanceClause,
genericWhereClause: node.genericWhereClause,
memberBlock: node.memberBlock
)
return .visitChildren
}
override func visit(_ node: MacroDeclSyntax) -> SyntaxVisitorContinueKind {
// Macro declarations have a syntax that combines the best parts of types and functions while
// adding their own unique flavor, so we have to copy and adapt the relevant parts of those
// `arrange*` functions here.
before(node.firstToken(viewMode: .sourceAccurate), tokens: .open)
arrangeAttributeList(node.attributes, separateByLineBreaks: config.lineBreakBeforeEachArgument)
let hasArguments = !node.signature.parameterClause.parameters.isEmpty
// Prioritize keeping ") -> <return_type>" together. We can only do this if the macro has
// arguments.
if hasArguments && config.prioritizeKeepingFunctionOutputTogether {
// Due to visitation order, the matching .open break is added in ParameterClauseSyntax.
after(node.signature.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
let mustBreak = node.signature.returnClause != nil || node.definition != nil
arrangeParameterClause(node.signature.parameterClause, forcesBreakBeforeRightParen: mustBreak)
// Prioritize keeping "<modifiers> macro <name>(" together. Also include the ")" if the
// parameter list is empty.
let firstTokenAfterAttributes =
node.modifiers.firstToken(viewMode: .sourceAccurate) ?? node.macroKeyword
before(firstTokenAfterAttributes, tokens: .open)
after(node.macroKeyword, tokens: .break)
if hasArguments || node.genericParameterClause != nil {
after(node.signature.parameterClause.leftParen, tokens: .close)
} else {
after(node.signature.parameterClause.rightParen, tokens: .close)
}
if let genericWhereClause = node.genericWhereClause {
before(genericWhereClause.firstToken(viewMode: .sourceAccurate), tokens: .break(.same), .open)
after(genericWhereClause.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
if let definition = node.definition {
// Start the group *after* the `=` so that it all wraps onto its own line if it doesn't fit.
after(definition.equal, tokens: .open)
after(definition.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
after(node.lastToken(viewMode: .sourceAccurate), tokens: .close)
return .visitChildren
}
/// Applies formatting tokens to the tokens in the given type declaration node (i.e., a class,
/// struct, enum, protocol, or extension).
private func arrangeTypeDeclBlock(
_ node: Syntax,
attributes: AttributeListSyntax?,
modifiers: DeclModifierListSyntax?,
typeKeyword: TokenSyntax,
identifier: TokenSyntax,
genericParameterOrPrimaryAssociatedTypeClause: Syntax?,
inheritanceClause: InheritanceClauseSyntax?,
genericWhereClause: GenericWhereClauseSyntax?,
memberBlock: MemberBlockSyntax
) {
before(node.firstToken(viewMode: .sourceAccurate), tokens: .open)
arrangeAttributeList(attributes, separateByLineBreaks: config.lineBreakBetweenDeclarationAttributes)
// Prioritize keeping "<modifiers> <keyword> <name>:" together (corresponding group close is
// below at `lastTokenBeforeBrace`).
let firstTokenAfterAttributes = modifiers?.firstToken(viewMode: .sourceAccurate) ?? typeKeyword
before(firstTokenAfterAttributes, tokens: .open)
after(typeKeyword, tokens: .break)
arrangeBracesAndContents(of: memberBlock, contentsKeyPath: \.members)
if let genericWhereClause = genericWhereClause {
before(genericWhereClause.firstToken(viewMode: .sourceAccurate), tokens: .break(.same), .open)
after(memberBlock.leftBrace, tokens: .close)
}
let lastTokenBeforeBrace =
inheritanceClause?.colon
?? genericParameterOrPrimaryAssociatedTypeClause?.lastToken(viewMode: .sourceAccurate)
?? identifier
after(lastTokenBeforeBrace, tokens: .close)
after(node.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
// MARK: - Function and function-like declaration nodes (initializers, deinitializers, subscripts)
override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
let hasArguments = !node.signature.parameterClause.parameters.isEmpty
// Prioritize keeping ") throws -> <return_type>" together. We can only do this if the function
// has arguments.
if hasArguments && config.prioritizeKeepingFunctionOutputTogether {
// Due to visitation order, the matching .open break is added in ParameterClauseSyntax.
after(node.signature.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
let mustBreak = node.body != nil || node.signature.returnClause != nil
arrangeParameterClause(node.signature.parameterClause, forcesBreakBeforeRightParen: mustBreak)
// Prioritize keeping "<modifiers> func <name>(" together. Also include the ")" if the parameter
// list is empty.
let firstTokenAfterAttributes = node.modifiers.firstToken(viewMode: .sourceAccurate) ?? node.funcKeyword
before(firstTokenAfterAttributes, tokens: .open)
after(node.funcKeyword, tokens: .break)
if hasArguments || node.genericParameterClause != nil {
after(node.signature.parameterClause.leftParen, tokens: .close)
} else {
after(node.signature.parameterClause.rightParen, tokens: .close)
}
// Add a non-breaking space after the identifier if it's an operator, to separate it visually
// from the following parenthesis or generic argument list. Note that even if the function is
// defining a prefix or postfix operator, the token kind always comes through as
// `binaryOperator`.
if case .binaryOperator = node.name.tokenKind {
after(node.name.lastToken(viewMode: .sourceAccurate), tokens: .space)
}
arrangeFunctionLikeDecl(
Syntax(node),
attributes: node.attributes,
genericWhereClause: node.genericWhereClause,
body: node.body,
bodyContentsKeyPath: \.statements
)
return .visitChildren
}
override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind {
let hasArguments = !node.signature.parameterClause.parameters.isEmpty
// Prioritize keeping ") throws" together. We can only do this if the function
// has arguments.
if hasArguments && config.prioritizeKeepingFunctionOutputTogether {
// Due to visitation order, the matching .open break is added in ParameterClauseSyntax.
after(node.signature.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
arrangeParameterClause(node.signature.parameterClause, forcesBreakBeforeRightParen: node.body != nil)
// Prioritize keeping "<modifiers> init<punctuation>" together.
let firstTokenAfterAttributes = node.modifiers.firstToken(viewMode: .sourceAccurate) ?? node.initKeyword
before(firstTokenAfterAttributes, tokens: .open)
if hasArguments || node.genericParameterClause != nil {
after(node.signature.parameterClause.leftParen, tokens: .close)
} else {
after(node.signature.parameterClause.rightParen, tokens: .close)
}
arrangeFunctionLikeDecl(
Syntax(node),
attributes: node.attributes,
genericWhereClause: node.genericWhereClause,
body: node.body,
bodyContentsKeyPath: \.statements
)
return .visitChildren
}
override func visit(_ node: DeinitializerDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeFunctionLikeDecl(
Syntax(node),
attributes: node.attributes,
genericWhereClause: nil,
body: node.body,
bodyContentsKeyPath: \.statements
)
return .visitChildren
}
override func visit(_ node: SubscriptDeclSyntax) -> SyntaxVisitorContinueKind {
let hasArguments = !node.parameterClause.parameters.isEmpty
before(node.firstToken(viewMode: .sourceAccurate), tokens: .open)
// Prioritize keeping "<modifiers> subscript" together.
if let firstModifierToken = node.modifiers.firstToken(viewMode: .sourceAccurate) {
before(firstModifierToken, tokens: .open)
if hasArguments || node.genericParameterClause != nil {
after(node.parameterClause.leftParen, tokens: .close)
} else {
after(node.parameterClause.rightParen, tokens: .close)
}
}
// Prioritize keeping ") -> <return_type>" together. We can only do this if the subscript has
// arguments.
if hasArguments && config.prioritizeKeepingFunctionOutputTogether {
// Due to visitation order, the matching .open break is added in ParameterClauseSyntax.
after(node.returnClause.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
arrangeAttributeList(node.attributes, separateByLineBreaks: config.lineBreakBetweenDeclarationAttributes)
if let genericWhereClause = node.genericWhereClause {
before(genericWhereClause.firstToken(viewMode: .sourceAccurate), tokens: .break(.same), .open)
after(genericWhereClause.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
before(node.returnClause.firstToken(viewMode: .sourceAccurate), tokens: .break)
if let accessorBlock = node.accessorBlock {
switch accessorBlock.accessors {
case .accessors(let accessors):
arrangeBracesAndContents(
leftBrace: accessorBlock.leftBrace,
accessors: accessors,
rightBrace: accessorBlock.rightBrace
)
case .getter:
arrangeBracesAndContents(of: accessorBlock, contentsKeyPath: \.getterCodeBlockItems)
}
}
after(node.lastToken(viewMode: .sourceAccurate), tokens: .close)
arrangeParameterClause(node.parameterClause, forcesBreakBeforeRightParen: true)
return .visitChildren
}
override func visit(_ node: AccessorEffectSpecifiersSyntax) -> SyntaxVisitorContinueKind {
arrangeEffectSpecifiers(node)
return .visitChildren
}
override func visit(_ node: FunctionEffectSpecifiersSyntax) -> SyntaxVisitorContinueKind {
arrangeEffectSpecifiers(node)
return .visitChildren
}
override func visit(_ node: TypeEffectSpecifiersSyntax) -> SyntaxVisitorContinueKind {
arrangeEffectSpecifiers(node)
return .visitChildren
}
/// Applies formatting tokens to the tokens in the given function or function-like declaration
/// node (e.g., initializers, deinitiailizers, and subscripts).
private func arrangeFunctionLikeDecl<Node: BracedSyntax, BodyContents: SyntaxCollection>(
_ node: Syntax,
attributes: AttributeListSyntax?,
genericWhereClause: GenericWhereClauseSyntax?,
body: Node?,
bodyContentsKeyPath: KeyPath<Node, BodyContents>?
) where BodyContents.Element: SyntaxProtocol {
before(node.firstToken(viewMode: .sourceAccurate), tokens: .open)
arrangeAttributeList(attributes, separateByLineBreaks: config.lineBreakBetweenDeclarationAttributes)
arrangeBracesAndContents(of: body, contentsKeyPath: bodyContentsKeyPath)
if let genericWhereClause = genericWhereClause {
before(genericWhereClause.firstToken(viewMode: .sourceAccurate), tokens: .break(.same), .open)
after(body?.leftBrace ?? genericWhereClause.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
after(node.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
/// Arranges the `async` and `throws` effect specifiers of a function or accessor declaration.
private func arrangeEffectSpecifiers<Node: EffectSpecifiersSyntax>(_ node: Node) {
before(node.asyncSpecifier, tokens: .break)
before(node.throwsClause?.throwsSpecifier, tokens: .break)
// Keep them together if both `async` and `throws` are present.
if let asyncSpecifier = node.asyncSpecifier, let throwsSpecifier = node.throwsClause?.throwsSpecifier {
before(asyncSpecifier, tokens: .open)
after(throwsSpecifier, tokens: .close)
}
}
// MARK: - Property and subscript accessor block nodes
override func visit(_ node: AccessorDeclListSyntax) -> SyntaxVisitorContinueKind {
for child in node.dropLast() {
// If the child doesn't have a body (it's just the `get`/`set` keyword), then we're in a
// protocol and we want to let them be placed on the same line if possible. Otherwise, we
// place a newline between each accessor.
let newlines: NewlineBehavior = child.body == nil ? .elective : .soft
after(child.lastToken(viewMode: .sourceAccurate), tokens: .break(.same, size: 1, newlines: newlines))
}
return .visitChildren
}
override func visit(_ node: AccessorDeclSyntax) -> SyntaxVisitorContinueKind {
arrangeAttributeList(node.attributes, separateByLineBreaks: config.lineBreakBetweenDeclarationAttributes)
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: AccessorParametersSyntax) -> SyntaxVisitorContinueKind {
return .visitChildren
}
// MARK: - Control flow statement nodes
override func visit(_ node: LabeledStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.colon, tokens: .space)
return .visitChildren
}
override func visit(_ node: IfExprSyntax) -> SyntaxVisitorContinueKind {
// There may be a consistent breaking group around this node, see `CodeBlockItemSyntax`. This
// group is necessary so that breaks around and inside of the conditions aren't forced to break
// when the if-stmt spans multiple lines.
before(node.conditions.firstToken(viewMode: .sourceAccurate), tokens: .open)
after(node.conditions.lastToken(viewMode: .sourceAccurate), tokens: .close)
after(node.ifKeyword, tokens: .space)
// Add break groups, using open continuation breaks, around any conditions after the first so
// that continuations inside of the conditions can stack in addition to continuations between
// the conditions. There are no breaks around the first condition because if-statements look
// better without a break between the "if" and the first condition.
for condition in node.conditions.dropFirst() {
before(condition.firstToken(viewMode: .sourceAccurate), tokens: .break(.open(kind: .continuation), size: 0))
after(condition.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false), size: 0))
}
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
if let elseKeyword = node.elseKeyword {
// Add a token before the else keyword. Breaking before `else` is explicitly allowed when
// there's a comment.
if config.lineBreakBeforeControlFlowKeywords {
before(elseKeyword, tokens: .break(.same, newlines: .soft))
} else if elseKeyword.hasPrecedingLineComment {
before(elseKeyword, tokens: .break(.same, size: 1))
} else {
before(elseKeyword, tokens: .space)
}
// Breaks are only allowed after `else` when there's a comment; otherwise there shouldn't be
// any newlines between `else` and the open brace or a following `if`.
if let tokenAfterElse = elseKeyword.nextToken(viewMode: .all),
tokenAfterElse.hasPrecedingLineComment
{
after(node.elseKeyword, tokens: .break(.same, size: 1))
} else if let elseBody = node.elseBody, elseBody.is(IfExprSyntax.self) {
after(node.elseKeyword, tokens: .space)
}
}
arrangeBracesAndContents(of: node.elseBody?.as(CodeBlockSyntax.self), contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: GuardStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.guardKeyword, tokens: .space)
// Add break groups, using open continuation breaks, around all conditions so that continuations
// inside of the conditions can stack in addition to continuations between the conditions.
for condition in node.conditions {
before(condition.firstToken(viewMode: .sourceAccurate), tokens: .break(.open(kind: .continuation), size: 0))
after(condition.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false), size: 0))
}
before(node.elseKeyword, tokens: .break(.reset), .open)
after(node.elseKeyword, tokens: .space)
before(node.body.leftBrace, tokens: .close)
arrangeBracesAndContents(
of: node.body,
contentsKeyPath: \.statements,
shouldResetBeforeLeftBrace: false
)
return .visitChildren
}
override func visit(_ node: ForStmtSyntax) -> SyntaxVisitorContinueKind {
// If we have a `(try) await` clause, allow breaking after the `for` so that the `(try) await`
// can fall onto the next line if needed, and if both `try await` are present, keep them
// together. Otherwise, keep `for` glued to the token after it so that we break somewhere later
// on the line.
if let awaitKeyword = node.awaitKeyword {
after(node.forKeyword, tokens: .break)
if let tryKeyword = node.tryKeyword {
before(tryKeyword, tokens: .open)
after(tryKeyword, tokens: .break)
after(awaitKeyword, tokens: .close, .break)
} else {
after(awaitKeyword, tokens: .break)
}
} else {
after(node.forKeyword, tokens: .space)
}
after(node.caseKeyword, tokens: .space)
before(node.inKeyword, tokens: .break)
after(node.inKeyword, tokens: .space)
if let typeAnnotation = node.typeAnnotation {
after(
typeAnnotation.colon,
tokens: .break(.open(kind: .continuation), newlines: .elective(ignoresDiscretionary: true))
)
after(typeAnnotation.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false), size: 0))
}
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: WhileStmtSyntax) -> SyntaxVisitorContinueKind {
after(node.whileKeyword, tokens: .space)
// Add break groups, using open continuation breaks, around any conditions after the first so
// that continuations inside of the conditions can stack in addition to continuations between
// the conditions. There are no breaks around the first condition because there was historically
// not break after the while token and adding such a break would cause excessive changes to
// previously formatted code.
// This has the side effect that the label + `while` + tokens up to the first break in the first
// condition could be longer than the column limit since there are no breaks between the label
// or while token.
for condition in node.conditions.dropFirst() {
before(condition.firstToken(viewMode: .sourceAccurate), tokens: .break(.open(kind: .continuation), size: 0))
after(condition.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false), size: 0))
}
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: RepeatStmtSyntax) -> SyntaxVisitorContinueKind {
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
if config.lineBreakBeforeControlFlowKeywords {
before(node.whileKeyword, tokens: .break(.same), .open)
after(node.condition.lastToken(viewMode: .sourceAccurate), tokens: .close)
} else {
// The length of the condition needs to force the breaks around the braces of the repeat
// stmt's body, so that there's always a break before the right brace when the while &
// condition is too long to be on one line.
before(node.whileKeyword, tokens: .space)
// The `open` token occurs after the ending tokens for the braced `body` node.
before(node.body.rightBrace, tokens: .open)
after(node.condition.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
after(node.whileKeyword, tokens: .space)
return .visitChildren
}
override func visit(_ node: DoStmtSyntax) -> SyntaxVisitorContinueKind {
if node.throwsClause != nil {
after(node.doKeyword, tokens: .break(.same, size: 1))
}
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: CatchClauseSyntax) -> SyntaxVisitorContinueKind {
let catchPrecedingBreak =
config.lineBreakBeforeControlFlowKeywords
? Token.break(.same, newlines: .soft) : Token.space
before(node.catchKeyword, tokens: catchPrecedingBreak)
// If there are multiple items in the `catch` clause, wrap each in open/close breaks so that
// their internal breaks stack correctly. Otherwise, if there is only a single clause, use the
// old (pre-SE-0276) behavior (a fixed space after the `catch` keyword).
if node.catchItems.count > 1 {
for catchItem in node.catchItems {
before(catchItem.firstToken(viewMode: .sourceAccurate), tokens: .break(.open(kind: .continuation)))
after(catchItem.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false), size: 0))
}
} else {
before(node.catchItems.firstToken(viewMode: .sourceAccurate), tokens: .space)
}
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: DeferStmtSyntax) -> SyntaxVisitorContinueKind {
arrangeBracesAndContents(of: node.body, contentsKeyPath: \.statements)
return .visitChildren
}
override func visit(_ node: BreakStmtSyntax) -> SyntaxVisitorContinueKind {
before(node.label, tokens: .break)
return .visitChildren
}
override func visit(_ node: ReturnStmtSyntax) -> SyntaxVisitorContinueKind {
if let expression = node.expression {
if leftmostMultilineStringLiteral(of: expression) != nil {
before(expression.firstToken(viewMode: .sourceAccurate), tokens: .break(.open))
after(expression.lastToken(viewMode: .sourceAccurate), tokens: .break(.close(mustBreak: false)))
} else {
before(expression.firstToken(viewMode: .sourceAccurate), tokens: .break)
}
}
return .visitChildren
}
override func visit(_ node: ThrowStmtSyntax) -> SyntaxVisitorContinueKind {
before(node.expression.firstToken(viewMode: .sourceAccurate), tokens: .break)
return .visitChildren
}
override func visit(_ node: ContinueStmtSyntax) -> SyntaxVisitorContinueKind {
before(node.label, tokens: .break)
return .visitChildren
}
override func visit(_ node: SwitchExprSyntax) -> SyntaxVisitorContinueKind {
before(node.switchKeyword, tokens: .open)
after(node.switchKeyword, tokens: .space)
before(node.leftBrace, tokens: .break(.reset))
after(node.leftBrace, tokens: .close)
// An if-configuration clause around a switch-case encloses the case's node, so an
// if-configuration clause requires a break here in order to be allowed on a new line.
for ifConfigDecl in node.cases where ifConfigDecl.is(IfConfigDeclSyntax.self) {
if config.indentSwitchCaseLabels {
before(ifConfigDecl.firstToken(viewMode: .sourceAccurate), tokens: .break(.open))
after(ifConfigDecl.lastToken(viewMode: .sourceAccurate), tokens: .break(.close, size: 0))
} else {
before(ifConfigDecl.firstToken(viewMode: .sourceAccurate), tokens: .break(.same))
}
}
let newlines: NewlineBehavior =
areBracesCompletelyEmpty(node, contentsKeyPath: \.cases) ? .elective : .soft
before(node.rightBrace, tokens: .break(.same, size: 0, newlines: newlines))
return .visitChildren
}
override func visit(_ node: SwitchCaseSyntax) -> SyntaxVisitorContinueKind {
// If switch/case labels were configured to be indented, use an `open` break; otherwise, use
// the default `same` break.
let openBreak: Token
if config.indentSwitchCaseLabels {
openBreak = .break(.open, newlines: .elective)
} else {
openBreak = .break(.same, newlines: .soft)
}
before(node.firstToken(viewMode: .sourceAccurate), tokens: openBreak)
after(node.attribute?.lastToken(viewMode: .sourceAccurate), tokens: .space)
after(node.label.lastToken(viewMode: .sourceAccurate), tokens: .break(.reset, size: 0), .break(.open), .open)
// If switch/case labels were configured to be indented, insert an extra `close` break after
// the case body to match the `open` break above
var afterLastTokenTokens: [Token] = [.break(.close, size: 0), .close]
if config.indentSwitchCaseLabels {
afterLastTokenTokens.append(.break(.close, size: 0))
}
// If the case contains statements, add the closing tokens after the last token of the case.
// Otherwise, add the closing tokens before the next case (or the end of the switch) to have the
// same effect. If instead the opening and closing tokens were omitted completely in the absence
// of statements, comments within the empty case would be incorrectly indented to the same level
// as the case label.
if node.label.lastToken(viewMode: .sourceAccurate) != node.lastToken(viewMode: .sourceAccurate) {
after(node.lastToken(viewMode: .sourceAccurate), tokens: afterLastTokenTokens)
} else {
before(node.nextToken(viewMode: .sourceAccurate), tokens: afterLastTokenTokens)
}
return .visitChildren
}
override func visit(_ node: SwitchCaseLabelSyntax) -> SyntaxVisitorContinueKind {
before(node.caseKeyword, tokens: .open)
after(node.caseKeyword, tokens: .space)
// If an item with a `where` clause follows an item without a `where` clause, the compiler emits
// a warning telling the user that they should insert a newline between them to disambiguate
// their appearance. We enforce that "requirement" here to avoid spurious warnings, especially
// following a `NoCasesWithOnlyFallthrough` transformation that might merge cases.
let caseItems = Array(node.caseItems)
for (index, item) in caseItems.enumerated() {
before(item.firstToken(viewMode: .sourceAccurate), tokens: .open)
if let trailingComma = item.trailingComma {
// Insert a newline before the next item if it has a where clause and this item doesn't.
let nextItemHasWhereClause =
index + 1 < caseItems.endIndex && caseItems[index + 1].whereClause != nil
let requiresNewline = item.whereClause == nil && nextItemHasWhereClause
let newlines: NewlineBehavior = requiresNewline ? .soft : .elective
after(trailingComma, tokens: .close, .break(.continue, size: 1, newlines: newlines))
} else {
after(item.lastToken(viewMode: .sourceAccurate), tokens: .close)
}
}
after(node.colon, tokens: .close)
closingDelimiterTokens.insert(node.colon)
return .visitChildren
}
override func visit(_ node: YieldStmtSyntax) -> SyntaxVisitorContinueKind {
// As of https://github.com/swiftlang/swift-syntax/pull/895, the token following a `yield` keyword
// *must* be on the same line, so we cannot break here.
after(node.yieldKeyword, tokens: .space)
return .visitChildren
}
// TODO: - Other nodes (yet to be organized)
override func visit(_ node: DeclNameArgumentsSyntax) -> SyntaxVisitorContinueKind {
after(node.leftParen, tokens: .break(.open, size: 0), .open(argumentListConsistency()))
before(node.rightParen, tokens: .break(.close(mustBreak: false), size: 0), .close)
insertTokens(.break(.same, size: 0), betweenElementsOf: node.arguments)
return .visitChildren
}
override func visit(_ node: TupleExprSyntax) -> SyntaxVisitorContinueKind {
// We'll do nothing if it's a zero-element tuple, because we just want to keep the empty `()`
// together.
let elementCount = node.elements.count
if elementCount == 1 {
// A tuple with one element is a parenthesized expression; add a group around it to keep it
// together when possible, but breaks are handled elsewhere (see calls to
// `stackedIndentationBehavior`).
after(node.leftParen, tokens: .open)
before(node.rightParen, tokens: .close)
closingDelimiterTokens.insert(node.rightParen)
// When there's a comment inside of a parenthesized expression, we want to allow the comment
// to exist at the EOL with the left paren or on its own line. The contents are always
// indented on the following lines, since parens always create a scope. An open/close break
// pair isn't used here to avoid forcing the closing paren down onto a new line.
if node.leftParen.nextToken(viewMode: .all)?.hasPrecedingLineComment ?? false {
after(node.leftParen, tokens: .break(.continue, size: 0))
}
} else if elementCount > 1 {
// Tuples with more than one element are "true" tuples, and should indent as block structures.
after(node.leftParen, tokens: .break(.open, size: 0), .open)
before(node.rightParen, tokens: .break(.close, size: 0), .close)
insertTokens(.break(.same), betweenElementsOf: node.elements)
for element in node.elements {
arrangeAsTupleExprElement(element)
}
}
return .visitChildren
}
override func visit(_ node: LabeledExprListSyntax) -> SyntaxVisitorContinueKind {
// Intentionally do nothing here. Since `TupleExprElement`s are used both in tuple expressions
// and function argument lists, which need to be formatted, differently, those nodes manually
// loop over the nodes and arrange them in those contexts.
return .visitChildren
}
override func visit(_ node: LabeledExprSyntax) -> SyntaxVisitorContinueKind {
// Intentionally do nothing here. Since `TupleExprElement`s are used both in tuple expressions
// and function argument lists, which need to be formatted, differently, those nodes manually
// loop over the nodes and arrange them in those contexts.
return .visitChildren
}
/// Arranges the given tuple expression element as a tuple element (rather than a function call
/// argument).
///
/// - Parameter node: The tuple expression element to be arranged.
private func arrangeAsTupleExprElement(_ node: LabeledExprSyntax) {
before(node.firstToken(viewMode: .sourceAccurate), tokens: .open)
after(node.colon, tokens: .break)
after(node.lastToken(viewMode: .sourceAccurate), tokens: .close)
if let trailingComma = node.trailingComma {
closingDelimiterTokens.insert(trailingComma)
}
}
override func visit(_ node: ArrayExprSyntax) -> SyntaxVisitorContinueKind {
if !node.elements.isEmpty || node.rightSquare.hasAnyPrecedingComment {
after(node.leftSquare, tokens: .break(.open, size: 0), .open)
before(node.rightSquare, tokens: .break(.close, size: 0), .close)
}
return .visitChildren
}
override func visit(_ node: ArrayElementListSyntax) -> SyntaxVisitorContinueKind {
insertTokens(.break(.same), betweenElementsOf: node)
for element in node {
before(element.firstToken(viewMode: .sourceAccurate), tokens: .open)
after(element.lastToken(viewMode: .sourceAccurate), tokens: .close)
if let trailingComma = element.trailingComma {
closingDelimiterTokens.insert(trailingComma)
}
}
if let lastElement = node.last {
if let trailingComma = lastElement.trailingComma {
ignoredTokens.insert(trailingComma)
}
before(node.first?.firstToken(viewMode: .sourceAccurate), tokens: .commaDelimitedRegionStart)
let endToken =
Token.commaDelimitedRegionEnd(
hasTrailingComma: lastElement.trailingComma != nil,
isSingleElement: node.first == lastElement
)
after(lastElement.expression.lastToken(viewMode: .sourceAccurate), tokens: [endToken])
}
return .visitChildren
}
override func visit(_ node: ArrayElementSyntax) -> SyntaxVisitorContinueKind {
return .visitChildren
}
override func visit(_ node: DictionaryExprSyntax) -> SyntaxVisitorContinueKind {
// The node's content is either a `DictionaryElementListSyntax` or a `TokenSyntax` for a colon
// token (for an empty dictionary).
if !(node.content.as(DictionaryElementListSyntax.self)?.isEmpty ?? true)
|| node.content.hasAnyPrecedingComment
|| node.rightSquare.hasAnyPrecedingComment
{
after(node.leftSquare, tokens: .break(.open, size: 0), .open)
before(node.rightSquare, tokens: .break(.close, size: 0), .close)
}
return .visitChildren
}