-
Notifications
You must be signed in to change notification settings - Fork 617
/
Rules.swift
5285 lines (5076 loc) · 247 KB
/
Rules.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
//
// Rules.swift
// SwiftFormat
//
// Created by Nick Lockwood on 12/08/2016.
// Copyright 2016 Nick Lockwood
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/nicklockwood/SwiftFormat
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public final class FormatRule: Equatable, Comparable {
private let fn: (Formatter) -> Void
fileprivate(set) var name = ""
fileprivate(set) var index = 0
let help: String
let runOnceOnly: Bool
let disabledByDefault: Bool
let orderAfter: [String]
let options: [String]
let sharedOptions: [String]
let deprecationMessage: String?
var isDeprecated: Bool {
return deprecationMessage != nil
}
fileprivate init(help: String,
deprecationMessage: String? = nil,
runOnceOnly: Bool = false,
disabledByDefault: Bool = false,
orderAfter: [String] = [],
options: [String] = [],
sharedOptions: [String] = [],
_ fn: @escaping (Formatter) -> Void)
{
self.fn = fn
self.help = help
self.runOnceOnly = runOnceOnly
self.disabledByDefault = disabledByDefault || deprecationMessage != nil
self.orderAfter = orderAfter
self.options = options
self.sharedOptions = sharedOptions
self.deprecationMessage = deprecationMessage
}
public func apply(with formatter: Formatter) {
formatter.currentRule = self
fn(formatter)
formatter.currentRule = nil
}
public static func == (lhs: FormatRule, rhs: FormatRule) -> Bool {
return lhs === rhs
}
public static func < (lhs: FormatRule, rhs: FormatRule) -> Bool {
return lhs.index < rhs.index
}
}
public let FormatRules = _FormatRules()
private let rulesByName: [String: FormatRule] = {
var rules = [String: FormatRule]()
for (label, value) in Mirror(reflecting: FormatRules).children {
guard let name = label, let rule = value as? FormatRule else {
continue
}
rule.name = name
rules[name] = rule
}
let values = rules.values.sorted(by: { $0.name < $1.name })
for (index, value) in values.enumerated() {
value.index = index * 10
}
var changedOrder = true
while changedOrder {
changedOrder = false
for value in values {
value.orderAfter.forEach { name in
guard let rule = rules[name] else {
preconditionFailure(name)
}
if rule.index >= value.index {
value.index = rule.index + 1
changedOrder = true
}
}
}
}
return rules
}()
private func allRules(except rules: [String]) -> [FormatRule] {
precondition(!rules.contains(where: { rulesByName[$0] == nil }))
return Array(rulesByName.keys.sorted().compactMap {
rules.contains($0) ? nil : rulesByName[$0]
})
}
private let _allRules = allRules(except: [])
private let _disabledByDefault = _allRules.filter { $0.disabledByDefault }.map { $0.name }
private let _defaultRules = allRules(except: _disabledByDefault)
public extension _FormatRules {
/// A Dictionary of rules by name
var byName: [String: FormatRule] { return rulesByName }
/// All rules
var all: [FormatRule] { return _allRules }
/// Default active rules
var `default`: [FormatRule] { return _defaultRules }
/// Rules that are disabled by default
var disabledByDefault: [String] { return _disabledByDefault }
/// Just the specified rules
func named(_ names: [String]) -> [FormatRule] {
return Array(names.sorted().compactMap { rulesByName[$0] })
}
/// All rules except those specified
func all(except rules: [String]) -> [FormatRule] {
return allRules(except: rules)
}
}
extension _FormatRules {
/// Get all format options used by a given set of rules
func optionsForRules(_ rules: [FormatRule]) -> [String] {
var options = Set<String>()
for rule in rules {
options.formUnion(rule.options + rule.sharedOptions)
}
return options.sorted()
}
// Get shared-only options for a given set of rules
func sharedOptionsForRules(_ rules: [FormatRule]) -> [String] {
var options = Set<String>()
var sharedOptions = Set<String>()
for rule in rules {
options.formUnion(rule.options)
sharedOptions.formUnion(rule.sharedOptions)
}
sharedOptions.subtract(options)
return sharedOptions.sorted()
}
}
public struct _FormatRules {
fileprivate init() {}
/// Implement the following rules with respect to the spacing around parens:
/// * There is no space between an opening paren and the preceding identifier,
/// unless the identifier is one of the specified keywords
/// * There is no space between an opening paren and the preceding closing brace
/// * There is no space between an opening paren and the preceding closing square bracket
/// * There is space between a closing paren and following identifier
/// * There is space between a closing paren and following opening brace
/// * There is no space between a closing paren and following opening square bracket
public let spaceAroundParens = FormatRule(
help: "Add or remove space around parentheses."
) { formatter in
func spaceAfter(_ keyword: String, index: Int) -> Bool {
switch keyword {
case "@autoclosure":
if let nextIndex = formatter.index(of: .nonSpaceOrLinebreak, after: index),
formatter.next(.nonSpaceOrCommentOrLinebreak, after: nextIndex) == .identifier("escaping")
{
assert(formatter.tokens[nextIndex] == .startOfScope("("))
return false
}
return true
case "@escaping", "@noescape":
return true
case "private", "fileprivate", "internal",
"init", "subscript":
return false
default:
return keyword.first.map { !"@#".contains($0) } ?? true
}
}
func isCaptureList(at i: Int) -> Bool {
assert(formatter.tokens[i] == .endOfScope("]"))
guard formatter.lastToken(before: i + 1, where: {
!$0.isSpaceOrCommentOrLinebreak && $0 != .endOfScope("]")
}) == .startOfScope("{"),
let nextToken = formatter.nextToken(after: i, where: {
!$0.isSpaceOrCommentOrLinebreak && $0 != .startOfScope("(")
}),
[.operator("->", .infix), .keyword("throws"), .keyword("rethrows"), .keyword("in")].contains(nextToken)
else { return false }
return true
}
formatter.forEach(.startOfScope("(")) { i, token in
guard let prevToken = formatter.token(at: i - 1) else {
return
}
switch prevToken {
case let .keyword(string) where spaceAfter(string, index: i - 1):
fallthrough
case .endOfScope("]") where isCaptureList(at: i - 1),
.endOfScope(")") where formatter.isAttribute(at: i - 1):
formatter.insert(.space(" "), at: i)
case .space:
if let token = formatter.token(at: i - 2) {
switch token {
case let .keyword(string) where !spaceAfter(string, index: i - 2):
fallthrough
case .identifier, .number:
fallthrough
case .endOfScope("}"), .endOfScope(">"),
.endOfScope("]") where !isCaptureList(at: i - 2),
.endOfScope(")") where !formatter.isAttribute(at: i - 2):
formatter.removeToken(at: i - 1)
default:
break
}
}
default:
break
}
}
formatter.forEach(.endOfScope(")")) { i, _ in
guard let nextToken = formatter.token(at: i + 1) else {
return
}
switch nextToken {
case .identifier, .keyword, .startOfScope("{"):
formatter.insert(.space(" "), at: i + 1)
case .space where formatter.token(at: i + 2) == .startOfScope("["):
formatter.removeToken(at: i + 1)
default:
break
}
}
}
/// Remove space immediately inside parens
public let spaceInsideParens = FormatRule(
help: "Remove space inside parentheses."
) { formatter in
formatter.forEach(.startOfScope("(")) { i, _ in
if formatter.token(at: i + 1)?.isSpace == true,
formatter.token(at: i + 2)?.isComment == false
{
formatter.removeToken(at: i + 1)
}
}
formatter.forEach(.endOfScope(")")) { i, _ in
if formatter.token(at: i - 1)?.isSpace == true,
formatter.token(at: i - 2)?.isCommentOrLinebreak == false
{
formatter.removeToken(at: i - 1)
}
}
}
/// Implement the following rules with respect to the spacing around square brackets:
/// * There is no space between an opening bracket and the preceding identifier,
/// unless the identifier is one of the specified keywords
/// * There is no space between an opening bracket and the preceding closing brace
/// * There is no space between an opening bracket and the preceding closing square bracket
/// * There is space between a closing bracket and following identifier
/// * There is space between a closing bracket and following opening brace
public let spaceAroundBrackets = FormatRule(
help: "Add or remove space around square brackets."
) { formatter in
formatter.forEach(.startOfScope("[")) { i, token in
guard let prevToken = formatter.token(at: i - 1) else {
return
}
switch prevToken {
case .keyword:
formatter.insert(.space(" "), at: i)
case .space:
if let token = formatter.token(at: i - 2) {
switch token {
case .identifier, .number, .endOfScope("]"), .endOfScope("}"), .endOfScope(")"):
formatter.removeToken(at: i - 1)
default:
break
}
}
default:
break
}
}
formatter.forEach(.endOfScope("]")) { i, _ in
guard let nextToken = formatter.token(at: i + 1) else {
return
}
switch nextToken {
case .identifier, .keyword, .startOfScope("{"):
formatter.insert(.space(" "), at: i + 1)
case .space where formatter.token(at: i + 2) == .startOfScope("["):
formatter.removeToken(at: i + 1)
default:
break
}
}
}
/// Remove space immediately inside square brackets
public let spaceInsideBrackets = FormatRule(
help: "Remove space inside square brackets."
) { formatter in
formatter.forEach(.startOfScope("[")) { i, _ in
if formatter.token(at: i + 1)?.isSpace == true,
formatter.token(at: i + 2)?.isComment == false
{
formatter.removeToken(at: i + 1)
}
}
formatter.forEach(.endOfScope("]")) { i, _ in
if formatter.token(at: i - 1)?.isSpace == true,
formatter.token(at: i - 2)?.isCommentOrLinebreak == false
{
formatter.removeToken(at: i - 1)
}
}
}
/// Ensure that there is space between an opening brace and the preceding
/// identifier, and between a closing brace and the following identifier.
public let spaceAroundBraces = FormatRule(
help: "Add or remove space around curly braces."
) { formatter in
formatter.forEach(.startOfScope("{")) { i, _ in
if let prevToken = formatter.token(at: i - 1) {
switch prevToken {
case .space, .linebreak,
.startOfScope where !prevToken.isStringDelimiter:
break
default:
formatter.insert(.space(" "), at: i)
}
}
}
formatter.forEach(.endOfScope("}")) { i, _ in
if let nextToken = formatter.token(at: i + 1) {
switch nextToken {
case .identifier, .keyword:
formatter.insert(.space(" "), at: i + 1)
default:
break
}
}
}
}
/// Ensure that there is space immediately inside braces
public let spaceInsideBraces = FormatRule(
help: "Add space inside curly braces."
) { formatter in
formatter.forEach(.startOfScope("{")) { i, _ in
if let nextToken = formatter.token(at: i + 1) {
if !nextToken.isSpaceOrLinebreak,
![.endOfScope("}"), .startOfScope("{")].contains(nextToken)
{
formatter.insert(.space(" "), at: i + 1)
}
}
}
formatter.forEach(.endOfScope("}")) { i, _ in
if let prevToken = formatter.token(at: i - 1) {
if !prevToken.isSpaceOrLinebreak,
![.endOfScope("}"), .startOfScope("{")].contains(prevToken)
{
formatter.insert(.space(" "), at: i)
}
}
}
}
/// Ensure there is no space between an opening chevron and the preceding identifier
public let spaceAroundGenerics = FormatRule(
help: "Remove space around angle brackets."
) { formatter in
formatter.forEach(.startOfScope("<")) { i, _ in
if formatter.token(at: i - 1)?.isSpace == true,
formatter.token(at: i - 2)?.isIdentifierOrKeyword == true
{
formatter.removeToken(at: i - 1)
}
}
}
/// Remove space immediately inside chevrons
public let spaceInsideGenerics = FormatRule(
help: "Remove space inside angle brackets."
) { formatter in
formatter.forEach(.startOfScope("<")) { i, _ in
if formatter.token(at: i + 1)?.isSpace == true {
formatter.removeToken(at: i + 1)
}
}
formatter.forEach(.endOfScope(">")) { i, _ in
if formatter.token(at: i - 1)?.isSpace == true,
formatter.token(at: i - 2)?.isLinebreak == false
{
formatter.removeToken(at: i - 1)
}
}
}
/// Implement the following rules with respect to the spacing around operators:
/// * Infix operators are separated from their operands by a space on either
/// side. Does not affect prefix/postfix operators, as required by syntax.
/// * Delimiters, such as commas and colons, are consistently followed by a
/// single space, unless it appears at the end of a line, and is not
/// preceded by a space, unless it appears at the beginning of a line.
public let spaceAroundOperators = FormatRule(
help: "Add or remove space around operators or delimiters.",
options: ["operatorfunc", "nospaceoperators", "ranges"]
) { formatter in
formatter.forEachToken { i, token in
switch token {
case .operator(_, .none):
switch formatter.token(at: i + 1) {
case nil, .linebreak?, .endOfScope?, .operator?, .delimiter?,
.startOfScope("(")? where !formatter.options.spaceAroundOperatorDeclarations:
break
case .space?:
switch formatter.next(.nonSpaceOrLinebreak, after: i) {
case nil, .linebreak?, .endOfScope?, .delimiter?,
.startOfScope("(")? where !formatter.options.spaceAroundOperatorDeclarations:
formatter.removeToken(at: i + 1)
default:
break
}
default:
formatter.insert(.space(" "), at: i + 1)
}
case .operator("?", .postfix), .operator("!", .postfix):
if let prevToken = formatter.token(at: i - 1),
formatter.token(at: i + 1)?.isSpaceOrLinebreak == false,
[.keyword("as"), .keyword("try")].contains(prevToken)
{
formatter.insert(.space(" "), at: i + 1)
}
case .operator(".", _):
if formatter.token(at: i + 1)?.isSpace == true {
formatter.removeToken(at: i + 1)
}
guard let prevIndex = formatter.index(of: .nonSpace, before: i) else {
formatter.removeTokens(in: 0 ..< i)
break
}
let spaceRequired: Bool
switch formatter.tokens[prevIndex] {
case .operator(_, .infix), .startOfScope:
return
case let token where token.isUnwrapOperator:
if let prevToken = formatter.last(.nonSpace, before: prevIndex),
[.keyword("try"), .keyword("as")].contains(prevToken)
{
spaceRequired = true
} else {
spaceRequired = false
}
case .operator(_, .prefix):
spaceRequired = false
case let token:
spaceRequired = !token.isAttribute && !token.isLvalue
}
if formatter.token(at: i - 1)?.isSpaceOrLinebreak == true {
if !spaceRequired {
formatter.removeToken(at: i - 1)
}
} else if spaceRequired {
formatter.insertSpace(" ", at: i)
}
case .operator("?", .infix):
break // Spacing around ternary ? is not optional
case let .operator(name, .infix) where formatter.options.noSpaceOperators.contains(name) ||
(!formatter.options.spaceAroundRangeOperators && token.isRangeOperator):
if formatter.token(at: i + 1)?.isSpace == true,
formatter.token(at: i - 1)?.isSpace == true,
let nextToken = formatter.next(.nonSpace, after: i),
!nextToken.isCommentOrLinebreak, !nextToken.isOperator,
let prevToken = formatter.last(.nonSpace, before: i),
!prevToken.isCommentOrLinebreak, !prevToken.isOperator || prevToken.isUnwrapOperator
{
formatter.removeToken(at: i + 1)
formatter.removeToken(at: i - 1)
}
case .operator(_, .infix):
if formatter.token(at: i + 1)?.isSpaceOrLinebreak == false {
formatter.insert(.space(" "), at: i + 1)
}
if formatter.token(at: i - 1)?.isSpaceOrLinebreak == false {
formatter.insert(.space(" "), at: i)
}
case .operator(_, .prefix):
if let prevIndex = formatter.index(of: .nonSpace, before: i, if: {
[.startOfScope("["), .startOfScope("("), .startOfScope("<")].contains($0)
}) {
formatter.removeTokens(in: prevIndex + 1 ..< i)
} else if formatter.token(at: i - 1)?.isSpaceOrLinebreak == false {
formatter.insert(.space(" "), at: i)
}
case .delimiter(":"):
// TODO: make this check more robust, and remove redundant space
if formatter.token(at: i + 1)?.isIdentifier == true,
formatter.token(at: i + 2) == .delimiter(":")
{
// It's a selector
break
}
fallthrough
case .operator(_, .postfix), .delimiter(","), .delimiter(";"), .startOfScope(":"):
switch formatter.token(at: i + 1) {
case nil, .space?, .linebreak?, .endOfScope?, .operator?, .delimiter?:
break
default:
// Ensure there is a space after the token
formatter.insert(.space(" "), at: i + 1)
}
if formatter.token(at: i - 1)?.isSpace == true,
formatter.token(at: i - 2)?.isLinebreak == false
{
// Remove space before the token
formatter.removeToken(at: i - 1)
}
default:
break
}
}
}
/// Add space around comments, except at the start or end of a line
public let spaceAroundComments = FormatRule(
help: "Add space before and/or after comments."
) { formatter in
formatter.forEach(.startOfScope("//")) { i, _ in
if let prevToken = formatter.token(at: i - 1), !prevToken.isSpaceOrLinebreak {
formatter.insert(.space(" "), at: i)
}
}
formatter.forEach(.endOfScope("*/")) { i, _ in
guard let startIndex = formatter.index(of: .startOfScope("/*"), before: i),
case let .commentBody(commentStart)? = formatter.next(.nonSpaceOrLinebreak, after: startIndex),
case let .commentBody(commentEnd)? = formatter.last(.nonSpaceOrLinebreak, before: i),
!commentStart.hasPrefix("@"), !commentEnd.hasSuffix("@")
else {
return
}
if let nextToken = formatter.token(at: i + 1) {
if !nextToken.isSpaceOrLinebreak {
if nextToken != .delimiter(",") {
formatter.insert(.space(" "), at: i + 1)
}
} else if formatter.next(.nonSpace, after: i + 1) == .delimiter(",") {
formatter.removeToken(at: i + 1)
}
}
if let prevToken = formatter.token(at: startIndex - 1), !prevToken.isSpaceOrLinebreak {
if case let .commentBody(text) = prevToken, text.last?.unicodeScalars.last?.isSpace == true {
return
}
formatter.insert(.space(" "), at: startIndex)
}
}
}
/// Add space inside comments, taking care not to mangle headerdoc or
/// carefully preformatted comments, such as star boxes, etc.
public let spaceInsideComments = FormatRule(
help: "Add leading and/or trailing space inside comments."
) { formatter in
formatter.forEach(.startOfScope("//")) { i, _ in
guard let nextToken = formatter.token(at: i + 1),
case let .commentBody(string) = nextToken else { return }
guard let first = string.first else { return }
if "/!:".contains(first) {
let nextIndex = string.index(after: string.startIndex)
if nextIndex < string.endIndex, case let next = string[nextIndex], !" \t/".contains(next) {
let string = String(string.first!) + " " + String(string.dropFirst())
formatter.replaceToken(at: i + 1, with: .commentBody(string))
}
} else if !" \t".contains(first), !string.hasPrefix("===") { // Special-case check for swift stdlib codebase
formatter.insert(.space(" "), at: i + 1)
}
}
formatter.forEach(.startOfScope("/*")) { i, _ in
guard let nextToken = formatter.token(at: i + 1), case let .commentBody(string) = nextToken,
!string.hasPrefix("---"), !string.hasPrefix("@"), !string.hasSuffix("---"), !string.hasSuffix("@")
else {
return
}
if let first = string.first, "*!:".contains(first) {
let nextIndex = string.index(after: string.startIndex)
if nextIndex < string.endIndex, case let next = string[nextIndex],
!" /t".contains(next), !string.hasPrefix("**"), !string.hasPrefix("*/")
{
let string = String(string.first!) + " " + String(string.dropFirst())
formatter.replaceToken(at: i + 1, with: .commentBody(string))
}
} else {
formatter.insert(.space(" "), at: i + 1)
}
if let i = formatter.index(of: .endOfScope("*/"), after: i), let prevToken = formatter.token(at: i - 1) {
if !prevToken.isSpaceOrLinebreak, !prevToken.string.hasSuffix("*") {
formatter.insert(.space(" "), at: i)
}
}
}
}
/// Removes explicit type declarations from initialization declarations
public let redundantType = FormatRule(
help: "Remove redundant type from variable declarations."
) { formatter in
formatter.forEachToken(where: { (token) -> Bool in
token == .keyword("var") || token == .keyword("let")
}) { i, _ in
guard let colonIndex = formatter.index(after: i, where: {
[.delimiter(":"), .operator("=", .infix)].contains($0)
}), formatter.tokens[colonIndex] == .delimiter(":"),
let equalsIndex = formatter.index(of: .operator("=", .infix), after: colonIndex),
let endIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, before: equalsIndex)
else { return }
// Check types match
var i = colonIndex, j = equalsIndex
while let typeIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, after: i),
typeIndex <= endIndex,
let valueIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, after: j)
{
guard formatter.tokens[typeIndex] == formatter.tokens[valueIndex] else {
return
}
i = typeIndex
j = valueIndex
}
guard i == endIndex else {
return
}
// Check for ternary
if let endOfExpression = formatter.endOfExpression(at: j, upTo: [.operator("?", .infix)]),
formatter.next(.nonSpaceOrCommentOrLinebreak, after: endOfExpression) == .operator("?", .infix)
{
return
}
formatter.removeTokens(in: colonIndex ... endIndex)
if formatter.tokens[colonIndex - 1].isSpace {
formatter.removeToken(at: colonIndex - 1)
}
}
}
/// Collapse all consecutive space characters to a single space, except at
/// the start of a line or inside a comment or string, as these have no semantic
/// meaning and lead to noise in commits.
public let consecutiveSpaces = FormatRule(
help: "Replace consecutive spaces with a single space."
) { formatter in
formatter.forEach(.space) { i, token in
switch token {
case .space(""):
formatter.removeToken(at: i)
case .space(" "):
break
default:
guard let prevToken = formatter.token(at: i - 1),
let nextToken = formatter.token(at: i + 1)
else {
return
}
switch prevToken {
case .linebreak, .startOfScope("/*"), .startOfScope("//"), .commentBody:
return
case .endOfScope("*/") where nextToken == .startOfScope("/*") &&
formatter.currentScope(at: i) == .startOfScope("/*"):
return
default:
break
}
switch nextToken {
case .linebreak, .endOfScope("*/"), .commentBody:
return
default:
formatter.replaceToken(at: i, with: .space(" "))
}
}
}
}
// Converts types used for hosting only static members into enums to avoid instantiation.
public let enumNamespaces = FormatRule(
help: "Converts types used for hosting only static members into enums."
) { formatter in
func rangeHostsOnlyStaticMembersAtTopLevel(_ range: Range<Int>) -> Bool {
// exit for empty declarations
guard formatter.next(.nonSpaceOrCommentOrLinebreak, in: range) != nil else {
return false
}
var j = range.startIndex
while j < range.endIndex, let token = formatter.token(at: j) {
if token == .startOfScope("{"),
let skip = formatter.index(of: .endOfScope, after: j, if: { $0 == .endOfScope("}") })
{
j = skip
continue
}
// exit if there's a explicit init
if token == .keyword("init") {
return false
} else if [.keyword("let"),
.keyword("var"),
.keyword("func")].contains(token),
!formatter.modifiersForType(at: j, contains: "static")
{
return false
}
j += 1
}
return true
}
func rangeContainsTypeInit(_ type: String, in range: Range<Int>) -> Bool {
for i in range {
guard case let .identifier(name) = formatter.tokens[i], [type, "Self"].contains(name) else {
continue
}
if let nextToken = formatter.next(.nonSpaceOrComment, after: i),
[.startOfScope("("), .identifier("init")].contains(nextToken)
{
return true
}
}
return false
}
formatter.forEachToken(where: { [.keyword("class"), .keyword("struct")].contains($0) }) { i, _ in
guard formatter.last(.keyword, before: i) != .keyword("import"),
// exit if class is a type modifier
let next = formatter.next(.nonSpaceOrCommentOrLinebreak, after: i), !next.isKeyword,
// exit for class as protocol conformance
formatter.last(.nonSpaceOrCommentOrLinebreak, before: i) != .delimiter(":"),
let braceIndex = formatter.index(after: i, where: { $0 == .startOfScope("{") }),
// exit if type is conforming any types
!formatter.tokens[i ... braceIndex].contains(.delimiter(":")),
let endIndex = formatter.index(after: braceIndex, where: { $0 == .endOfScope("}") }),
case let .identifier(name)? = formatter.next(.identifier, after: i + 1)
else {
return
}
let range = braceIndex + 1 ..< endIndex
if rangeHostsOnlyStaticMembersAtTopLevel(range), !rangeContainsTypeInit(name, in: range) {
formatter.replaceToken(at: i, with: .keyword("enum"))
if let finalIndex = formatter.indexOfModifier("final", forTypeAt: i) {
formatter.removeTokens(in: finalIndex ... finalIndex + 1)
}
}
}
}
/// Remove trailing space from the end of lines, as it has no semantic
/// meaning and leads to noise in commits.
public let trailingSpace = FormatRule(
help: "Remove trailing space at end of a line.",
orderAfter: ["wrap", "wrapArguments"],
options: ["trimwhitespace"]
) { formatter in
formatter.forEach(.space) { i, _ in
if formatter.token(at: i + 1)?.isLinebreak ?? true,
formatter.options.truncateBlankLines || formatter.token(at: i - 1)?.isLinebreak == false
{
formatter.removeToken(at: i)
}
}
}
/// Collapse all consecutive blank lines into a single blank line
public let consecutiveBlankLines = FormatRule(
help: "Replace consecutive blank lines with a single blank line."
) { formatter in
formatter.forEach(.linebreak) { i, _ in
guard let prevIndex = formatter.index(of: .nonSpace, before: i, if: { $0.isLinebreak }) else {
return
}
if let prevToken = formatter.last(.nonSpaceOrLinebreak, before: prevIndex) {
switch prevToken {
case .startOfScope where prevToken.isStringDelimiter, .stringBody:
return
default:
break
}
}
if let nextIndex = formatter.index(of: .nonSpace, after: i) {
if formatter.tokens[nextIndex].isLinebreak {
formatter.removeTokens(in: i + 1 ... nextIndex)
}
} else if !formatter.options.fragment {
formatter.removeTokens(in: i ..< formatter.tokens.count)
}
}
}
/// Remove blank lines immediately after an opening brace, bracket, paren or chevron
public let blankLinesAtStartOfScope = FormatRule(
help: "Remove leading blank line at the start of a scope.",
orderAfter: ["organizeDeclarations"]
) { formatter in
formatter.forEach(.startOfScope) { i, token in
guard ["{", "(", "[", "<"].contains(token.string),
let indexOfFirstLineBreak = formatter.index(of: .nonSpaceOrComment, after: i),
// If there is extra code on the same line, ignore it
formatter.tokens[indexOfFirstLineBreak].isLinebreak
else { return }
// Find next non-space token
var index = indexOfFirstLineBreak + 1
var indexOfLastLineBreak = indexOfFirstLineBreak
loop: while let token = formatter.token(at: index) {
switch token {
case .linebreak:
indexOfLastLineBreak = index
case .space:
break
default:
break loop
}
index += 1
}
if formatter.options.removeBlankLines, indexOfFirstLineBreak != indexOfLastLineBreak {
formatter.removeTokens(in: indexOfFirstLineBreak ..< indexOfLastLineBreak)
return
}
}
}
/// Remove blank lines immediately before a closing brace, bracket, paren or chevron
/// unless it's followed by more code on the same line (e.g. } else { )
public let blankLinesAtEndOfScope = FormatRule(
help: "Remove trailing blank line at the end of a scope.",
orderAfter: ["organizeDeclarations"]
) { formatter in
formatter.forEach(.endOfScope) { i, token in
guard ["}", ")", "]", ">"].contains(token.string),
// If there is extra code after the closing scope on the same line, ignore it
(formatter.next(.nonSpaceOrComment, after: i).map { $0.isLinebreak }) ?? true
else { return }
// Find previous non-space token
var index = i - 1
var indexOfFirstLineBreak: Int?
var indexOfLastLineBreak: Int?
loop: while let token = formatter.token(at: index) {
switch token {
case .linebreak:
indexOfFirstLineBreak = index
if indexOfLastLineBreak == nil {
indexOfLastLineBreak = index
}
case .space:
break
default:
break loop
}
index -= 1
}
if formatter.options.removeBlankLines,
let indexOfFirstLineBreak = indexOfFirstLineBreak,
indexOfFirstLineBreak != indexOfLastLineBreak
{
formatter.removeTokens(in: indexOfFirstLineBreak ..< indexOfLastLineBreak!)
return
}
}
}
/// Adds a blank line immediately after a closing brace, unless followed by another closing brace
public let blankLinesBetweenScopes = FormatRule(
help: """
Insert blank line before class, struct, enum, extension, protocol or function
declarations.
""",
sharedOptions: ["linebreaks"]
) { formatter in
var spaceableScopeStack = [true]
var isSpaceableScopeType = false
formatter.forEachToken(onlyWhereEnabled: false) { i, token in
switch token {
case .keyword("class"),
.keyword("struct"),
.keyword("extension"),
.keyword("enum"):
isSpaceableScopeType =
(formatter.last(.nonSpaceOrCommentOrLinebreak, before: i) != .keyword("import"))
case .keyword("func"), .keyword("var"):
isSpaceableScopeType = false
case .startOfScope("{"):
spaceableScopeStack.append(isSpaceableScopeType)
isSpaceableScopeType = false
case .endOfScope("}"):
spaceableScopeStack.removeLast()
guard spaceableScopeStack.last == true,
let openingBraceIndex = formatter.index(of: .startOfScope("{"), before: i),
formatter.lastIndex(of: .linebreak, in: openingBraceIndex + 1 ..< i) != nil
else {
// Inline braces
break
}
var i = i
if let nextTokenIndex = formatter.index(of: .nonSpace, after: i, if: {
$0 == .startOfScope("(")
}), let closingParenIndex = formatter.index(of:
.endOfScope(")"), after: nextTokenIndex)
{
i = closingParenIndex
}
guard let nextTokenIndex = formatter.index(of: .nonSpaceOrLinebreak, after: i) else {
break
}
switch formatter.tokens[nextTokenIndex] {
case .error, .endOfScope,
.operator(".", _), .delimiter(","), .delimiter(":"),
.keyword("else"), .keyword("catch"), .keyword("#else"):
break
case .keyword("while"):
if let previousBraceIndex = formatter.index(of: .startOfScope("{"), before: i),
formatter.last(.nonSpaceOrCommentOrLinebreak, before: previousBraceIndex)
!= .keyword("repeat")
{
fallthrough
}
default:
if formatter.isEnabled, formatter.options.insertBlankLines,
let firstLinebreakIndex = formatter.index(of: .linebreak, in: i + 1 ..< nextTokenIndex),
formatter.index(of: .linebreak, in: firstLinebreakIndex + 1 ..< nextTokenIndex) == nil
{
formatter.insertLinebreak(at: firstLinebreakIndex)
}
}
default:
break
}
}
}
/// Adds a blank line around MARK: comments
public let blankLinesAroundMark = FormatRule(
help: "Insert blank line before and after `MARK:` comments.",
sharedOptions: ["linebreaks"]
) { formatter in
formatter.forEachToken { i, token in
guard case let .commentBody(comment) = token, comment.hasPrefix("MARK:"),
let startIndex = formatter.index(of: .nonSpace, before: i),
formatter.tokens[startIndex] == .startOfScope("//") else { return }
if let nextIndex = formatter.index(of: .linebreak, after: i),
let nextToken = formatter.next(.nonSpace, after: nextIndex),
!nextToken.isLinebreak, nextToken != .endOfScope("}")
{
formatter.insertLinebreak(at: nextIndex)
}
if formatter.options.insertBlankLines,
let lastIndex = formatter.index(of: .linebreak, before: startIndex),
let lastToken = formatter.last(.nonSpace, before: lastIndex),
!lastToken.isLinebreak, lastToken != .startOfScope("{")
{
formatter.insertLinebreak(at: lastIndex)
}
}
}
/// Always end file with a linebreak, to avoid incompatibility with certain unix tools:
/// http://stackoverflow.com/questions/2287967/why-is-it-recommended-to-have-empty-line-in-the-end-of-file