forked from nicklockwood/SwiftFormat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInference.swift
1498 lines (1456 loc) · 67.2 KB
/
Inference.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
//
// Inference.swift
// SwiftFormat
//
// Created by Nick Lockwood on 07/08/2018.
// Copyright © 2018 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
/// Infer default options by examining the existing source
public func inferFormatOptions(from tokens: [Token]) -> FormatOptions {
var options = FormatOptions.default
inferFormatOptions(Inference.all, from: tokens, into: &options)
return options
}
func inferFormatOptions(_ options: [String], from tokens: [Token], into: inout FormatOptions) {
let formatter = Formatter(tokens)
for name in options {
Inference.byName[name]?.fn(formatter, &into)
}
}
private struct OptionInferrer {
let fn: (Formatter, inout FormatOptions) -> Void
init(_ fn: @escaping (Formatter, inout FormatOptions) -> Void) {
self.fn = fn
}
}
private struct Inference {
let indent = OptionInferrer { formatter, options in
var indents = [(indent: String, count: Int)]()
func increment(_ indent: String) {
for (i, element) in indents.enumerated() {
if element.indent == indent {
indents[i] = (indent, element.count + 1)
return
}
}
indents.append((indent, 0))
}
var previousLength = 0
var scopeStack = [Token]()
formatter.forEachToken { i, token in
switch token {
case .linebreak where scopeStack.isEmpty:
guard case let .space(string)? = formatter.token(at: i + 1) else {
break
}
if string.hasPrefix("\t") {
increment("\t")
} else {
let length = string.count
let delta = previousLength - length
if delta != 0 {
switch formatter.token(at: i + 2) ?? .space("") {
case .commentBody, .delimiter(","):
return
default:
break
}
switch formatter.last(.nonSpaceOrCommentOrLinebreak, before: i) ?? .space("") {
case .delimiter(","):
break
default:
increment(String(repeating: " ", count: abs(delta)))
previousLength = length
}
}
}
case .startOfScope("/*"):
scopeStack.append(token)
case .endOfScope:
if let scope = scopeStack.last, token.isEndOfScope(scope) {
scopeStack.removeLast()
}
default:
break
}
}
if let indent = indents.sorted(by: {
$0.count > $1.count
}).first.map({ $0.indent }) {
options.indent = indent
}
}
let linebreak = OptionInferrer { formatter, options in
var cr = 0, lf = 0, crlf = 0
formatter.forEachToken { _, token in
switch token {
case .linebreak("\n", _):
lf += 1
case .linebreak("\r", _):
cr += 1
case .linebreak("\r\n", _):
crlf += 1
default:
break
}
}
var max = lf
var linebreak = "\n"
if cr > max {
max = cr
linebreak = "\r"
}
if crlf > max {
max = crlf
linebreak = "\r\n"
}
options.linebreak = linebreak
}
let allowInlineSemicolons = OptionInferrer { formatter, options in
var allow = false
for (i, token) in formatter.tokens.enumerated() {
guard case .delimiter(";") = token else {
continue
}
if formatter.next(.nonSpaceOrComment, after: i)?.isLinebreak == false {
allow = true
break
}
}
options.allowInlineSemicolons = allow
}
let noSpaceOperators = OptionInferrer { formatter, options in
var spaced = [String: Int](), unspaced = [String: Int]()
formatter.forEach(.operator) { i, token in
guard case let .operator(name, .infix) = token, name != ".",
let nextToken = formatter.next(.nonSpaceOrCommentOrLinebreak, after: i),
nextToken.string != ")", nextToken.string != ","
else {
return
}
if formatter.token(at: i + 1)?.isSpaceOrLinebreak == true {
spaced[name, default: 0] += 1
} else {
unspaced[name, default: 0] += 1
}
}
var noSpaceOperators = Set<String>()
let operators = Set(spaced.keys).union(unspaced.keys)
for name in operators where unspaced[name, default: 0] > spaced[name, default: 0] + 1 {
noSpaceOperators.insert(name)
}
// Related pairs
let relatedPairs = [
("...", "..<"), ("*", "/"), ("*=", "/="), ("+", "-"), ("+=", "-="),
("==", "!="), ("<", ">"), ("<=", ">="), ("<<", ">>"),
]
for pair in relatedPairs {
if noSpaceOperators.contains(pair.0),
!noSpaceOperators.contains(pair.1),
!operators.contains(pair.1)
{
noSpaceOperators.insert(pair.1)
} else if noSpaceOperators.contains(pair.1),
!noSpaceOperators.contains(pair.0),
!operators.contains(pair.0)
{
noSpaceOperators.insert(pair.0)
}
}
options.noSpaceOperators = noSpaceOperators
}
let useVoid = OptionInferrer { formatter, options in
var voids = 0, tuples = 0
formatter.forEach(.identifier("Void")) { i, _ in
if let prevToken = formatter.last(.nonSpaceOrCommentOrLinebreak, before: i),
[.operator(".", .prefix), .operator(".", .infix), .keyword("typealias")].contains(prevToken)
{
return
}
voids += 1
}
formatter.forEach(.startOfScope("(")) { i, _ in
if let prevIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, before: i),
let prevToken = formatter.token(at: prevIndex), prevToken == .operator("->", .infix),
let nextIndex = formatter.index(of: .nonSpaceOrLinebreak, after: i),
let nextToken = formatter.token(at: nextIndex), nextToken.string == ")",
formatter.next(.nonSpaceOrCommentOrLinebreak, after: nextIndex) != .operator("->", .infix)
{
tuples += 1
}
}
options.useVoid = (voids >= tuples)
}
let trailingCommas = OptionInferrer { formatter, options in
var trailing = 0, noTrailing = 0
formatter.forEach(.endOfScope("]")) { i, _ in
guard let linebreakIndex = formatter.index(of: .nonSpaceOrComment, before: i),
case .linebreak = formatter.tokens[linebreakIndex],
let prevTokenIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, before: linebreakIndex + 1),
let token = formatter.token(at: prevTokenIndex)
else {
return
}
switch token.string {
case "[", ":":
break // do nothing
case ",":
trailing += 1
default:
noTrailing += 1
}
}
options.trailingCommas = (trailing >= noTrailing)
}
let truncateBlankLines = OptionInferrer { formatter, options in
var truncated = 0, untruncated = 0
var scopeStack = [Token]()
formatter.forEachToken { i, token in
switch token {
case .startOfScope:
scopeStack.append(token)
case .linebreak:
switch formatter.token(at: i + 1) {
case .space?:
if let nextToken = formatter.token(at: i + 2) {
if case .linebreak = nextToken {
untruncated += 1
}
} else {
untruncated += 1
}
case .linebreak?, nil:
truncated += 1
default:
break
}
default:
if let scope = scopeStack.last, token.isEndOfScope(scope) {
scopeStack.removeLast()
}
}
}
options.truncateBlankLines = (truncated >= untruncated)
}
let allmanBraces = OptionInferrer { formatter, options in
var allman = 0, knr = 0
formatter.forEach(.startOfScope("{")) { i, _ in
// Check this isn't an inline block
guard let closingBraceIndex = formatter.index(of: .endOfScope("}"), after: i),
formatter.index(of: .linebreak, in: i + 1 ..< closingBraceIndex) != nil
else {
return
}
// Ignore wrapped if/else/guard
if let keyword = formatter.lastSignificantKeyword(at: i - 1, excluding: ["else"]),
["if", "guard", "while", "let", "var", "case"].contains(keyword)
{
return
}
// Check if brace is wrapped
if let prevTokenIndex = formatter.index(of: .nonSpace, before: i),
let prevToken = formatter.token(at: prevTokenIndex)
{
switch prevToken {
case .identifier, .keyword, .endOfScope, .operator("?", .postfix), .operator("!", .postfix):
knr += 1
case .linebreak:
allman += 1
default:
break
}
}
}
options.allmanBraces = (allman > 1 && allman > knr)
}
let ifdefIndent = OptionInferrer { formatter, options in
var indented = 0, notIndented = 0, outdented = 0
formatter.forEach(.startOfScope("#if")) { i, _ in
if let indent = formatter.token(at: i - 1), case let .space(string) = indent,
!string.isEmpty
{
// Indented, check next line
if let nextLineIndex = formatter.index(of: .linebreak, after: i),
let nextIndex = formatter.index(of: .nonSpaceOrLinebreak, after: nextLineIndex)
{
switch formatter.tokens[nextIndex - 1] {
case let .space(innerString):
if innerString.isEmpty {
// Error?
return
} else if innerString == string {
notIndented += 1
} else {
// Assume more indented, as less would be a mistake
indented += 1
}
case .linebreak:
// Could be noindent or outdent
notIndented += 1
outdented += 1
default:
break
}
}
// Error?
return
}
// Not indented, check next line
if let nextLineIndex = formatter.index(of: .linebreak, after: i),
let nextIndex = formatter.index(of: .nonSpaceOrLinebreak, after: nextLineIndex)
{
switch formatter.tokens[nextIndex - 1] {
case let .space(string):
if string.isEmpty {
fallthrough
} else if string == formatter.options.indent {
// Could be indent or outdent
indented += 1
outdented += 1
} else {
// Assume more indented, as less would be a mistake
outdented += 1
}
case .linebreak:
// Could be noindent or outdent
notIndented += 1
outdented += 1
default:
break
}
}
// Error?
}
if notIndented > indented {
options.ifdefIndent = outdented > notIndented ? .outdent : .noIndent
} else {
options.ifdefIndent = outdented > indented ? .outdent : .indent
}
}
let wrapArguments = OptionInferrer { formatter, options in
options.wrapArguments = formatter.wrapMode(forParameters: false)
}
let wrapParameters = OptionInferrer { formatter, options in
options.wrapParameters = formatter.wrapMode(forParameters: true)
}
let wrapCollections = OptionInferrer { formatter, options in
options.wrapCollections = formatter.wrapMode(for: "[")
}
let closingParenOnSameLine = OptionInferrer { formatter, options in
var balanced = 0, sameLine = 0
formatter.forEach(.startOfScope("(")) { i, _ in
guard let closingBraceIndex = formatter.endOfScope(at: i),
let linebreakIndex = formatter.index(of: .linebreak, after: i),
formatter.index(of: .nonSpaceOrComment, after: i) == linebreakIndex
else {
return
}
if formatter.last(.nonSpaceOrComment, before: closingBraceIndex)?.isLinebreak == true {
balanced += 1
} else {
sameLine += 1
}
}
options.closingParenOnSameLine = (sameLine > balanced)
}
let uppercaseHex = OptionInferrer { formatter, options in
let prefix = "0x"
var uppercase = 0, lowercase = 0
formatter.forEachToken { _, token in
if case var .number(string, .hex) = token {
string = string
.replacingOccurrences(of: "p", with: "")
.replacingOccurrences(of: "P", with: "")
if string == string.lowercased() {
lowercase += 1
} else {
let value = string[prefix.endIndex ..< string.endIndex]
if value == value.uppercased() {
uppercase += 1
}
}
}
}
options.uppercaseHex = (uppercase >= lowercase)
}
let uppercaseExponent = OptionInferrer { formatter, options in
var uppercase = 0, lowercase = 0
formatter.forEachToken { _, token in
switch token {
case let .number(string, .decimal):
let characters = string.unicodeScalars
if characters.contains("e") {
lowercase += 1
} else if characters.contains("E") {
uppercase += 1
}
case let .number(string, .hex):
let characters = string.unicodeScalars
if characters.contains("p") {
lowercase += 1
} else if characters.contains("P") {
uppercase += 1
}
default:
break
}
}
options.uppercaseExponent = (uppercase > lowercase)
}
let decimalGrouping = OptionInferrer { formatter, options in
options.decimalGrouping = formatter.grouping(for: .decimal)
}
let binaryGrouping = OptionInferrer { formatter, options in
options.binaryGrouping = formatter.grouping(for: .binary)
}
let octalGrouping = OptionInferrer { formatter, options in
options.octalGrouping = formatter.grouping(for: .octal)
}
let hexGrouping = OptionInferrer { formatter, options in
options.hexGrouping = formatter.grouping(for: .hex)
}
let fractionGrouping = OptionInferrer { formatter, options in
options.fractionGrouping = formatter.hasGrouping(for: .fraction)
}
let exponentGrouping = OptionInferrer { formatter, options in
options.exponentGrouping = formatter.hasGrouping(for: .exponent)
}
let hoistPatternLet = OptionInferrer { formatter, options in
var hoisted = 0, unhoisted = 0
func hoistable(_ keyword: String, in range: CountableRange<Int>) -> Bool {
var count = 0, keywordFound = false, identifierFound = false
for index in range {
switch formatter.tokens[index] {
case .keyword(keyword):
keywordFound = true
case .identifier("_"):
break
case .identifier where formatter.last(.nonSpaceOrComment, before: index)?.string != ".":
identifierFound = true
if keywordFound {
count += 1
}
case .delimiter(","):
guard keywordFound || !identifierFound else { return false }
keywordFound = false
identifierFound = false
case .startOfScope("{"):
return false
default:
break
}
}
return (keywordFound || !identifierFound) && count > 0
}
formatter.forEach(.startOfScope("(")) { i, _ in
// Check if pattern starts with let/var
var startIndex = i
guard let endIndex = formatter.index(of: .endOfScope(")"), after: i) else { return }
if var prevIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, before: i) {
if case .identifier = formatter.tokens[prevIndex] {
prevIndex = formatter.index(of: .spaceOrCommentOrLinebreak, before: prevIndex) ?? -1
startIndex = prevIndex + 1
prevIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, before: startIndex) ?? 0
}
let prevToken = formatter.tokens[prevIndex]
switch prevToken {
case .keyword("let"), .keyword("var"):
guard let prevPrevToken = formatter.last(.nonSpaceOrCommentOrLinebreak, before: prevIndex),
[.keyword("case"), .endOfScope("case"), .delimiter(",")].contains(prevPrevToken)
else {
// Tuple assignment, not a pattern
return
}
hoisted += 1
case .keyword("case"), .endOfScope("case"), .delimiter(","):
if hoistable("let", in: i + 1 ..< endIndex) || hoistable("var", in: i + 1 ..< endIndex) {
unhoisted += 1
}
default:
return
}
}
}
options.hoistPatternLet = (hoisted >= unhoisted)
}
let stripUnusedArguments = OptionInferrer { formatter, options in
var functionArgsRemoved = 0, functionArgsKept = 0
var unnamedFunctionArgsRemoved = 0, unnamedFunctionArgsKept = 0
func removeUsed<T>(from argNames: inout [String], with associatedData: inout [T], in range: CountableRange<Int>) {
for i in range {
let token = formatter.tokens[i]
if case .identifier = token, let index = argNames.firstIndex(of: token.unescaped()),
formatter.last(.nonSpaceOrCommentOrLinebreak, before: i)?.isOperator(".") == false,
formatter.next(.nonSpaceOrCommentOrLinebreak, after: i) != .delimiter(":") ||
formatter.currentScope(at: i) == .startOfScope("[")
{
argNames.remove(at: index)
associatedData.remove(at: index)
if argNames.isEmpty {
break
}
}
}
}
// Function arguments
formatter.forEachToken { i, token in
guard case let .keyword(keyword) = token, ["func", "init", "subscript"].contains(keyword),
let startIndex = formatter.index(of: .startOfScope("("), after: i),
let endIndex = formatter.index(of: .endOfScope(")"), after: startIndex) else { return }
let isOperator = (keyword == "subscript") ||
(keyword == "func" && formatter.next(.nonSpaceOrCommentOrLinebreak, after: i)?.isOperator == true)
var index = startIndex
var argNames = [String]()
var nameIndices = [Int]()
while index < endIndex {
guard let externalNameIndex = formatter.index(of: .nonSpaceOrCommentOrLinebreak, after: index, if: {
if case .identifier = $0 { return true }
// Probably an empty argument list
return false
}) else { return }
guard let nextIndex =
formatter.index(of: .nonSpaceOrCommentOrLinebreak, after: externalNameIndex) else { return }
let nextToken = formatter.tokens[nextIndex]
switch nextToken {
case let .identifier(name):
if name == "_" {
functionArgsRemoved += 1
let externalNameToken = formatter.tokens[externalNameIndex]
if case .identifier("_") = externalNameToken {
unnamedFunctionArgsRemoved += 1
}
} else {
argNames.append(nextToken.unescaped())
nameIndices.append(externalNameIndex)
}
case .delimiter(":"):
let externalNameToken = formatter.tokens[externalNameIndex]
if case .identifier("_") = externalNameToken {
functionArgsRemoved += 1
unnamedFunctionArgsRemoved += 1
} else {
argNames.append(externalNameToken.unescaped())
nameIndices.append(externalNameIndex)
}
default:
return
}
index = formatter.index(of: .delimiter(","), after: index) ?? endIndex
}
guard !argNames.isEmpty, let bodyStartIndex = formatter.index(after: endIndex, where: {
switch $0 {
case .startOfScope("{"): // What we're looking for
return true
case .keyword("throws"),
.keyword("rethrows"),
.keyword("where"),
.keyword("is"):
return false // Keep looking
case .keyword:
return true // Not valid between end of arguments and start of body
default:
return false // Keep looking
}
}), formatter.tokens[bodyStartIndex] == .startOfScope("{"),
let bodyEndIndex = formatter.index(of: .endOfScope("}"), after: bodyStartIndex) else {
return
}
removeUsed(from: &argNames, with: &nameIndices, in: bodyStartIndex + 1 ..< bodyEndIndex)
for index in nameIndices.reversed() {
functionArgsKept += 1
if case .identifier("_") = formatter.tokens[index] {
unnamedFunctionArgsKept += 1
}
}
}
if functionArgsRemoved >= functionArgsKept {
options.stripUnusedArguments = .all
} else if unnamedFunctionArgsRemoved >= unnamedFunctionArgsKept {
options.stripUnusedArguments = .unnamedOnly
} else {
// TODO: infer not removing args at all
options.stripUnusedArguments = .closureOnly
}
}
let explicitSelf = OptionInferrer { formatter, options in
func processBody(at index: inout Int, localNames: Set<String>, members: Set<String>,
typeStack: inout [String],
membersByType: inout [String: Set<String>],
classMembersByType: inout [String: Set<String>],
removed: inout Int, unremoved: inout Int,
initRemoved: inout Int, initUnremoved: inout Int,
isTypeRoot: Bool,
isInit: Bool)
{
var selfRequired: Set<String> { formatter.options.selfRequired }
let currentScope = formatter.currentScope(at: index)
let isWhereClause = index > 0 && formatter.tokens[index - 1] == .keyword("where")
assert(isWhereClause || currentScope.map { token -> Bool in
[.startOfScope("{"), .startOfScope(":")].contains(token)
} ?? true)
// Gather members & local variables
let type = (isTypeRoot && typeStack.count == 1) ? typeStack.first : nil
var members = type.flatMap { membersByType[$0] } ?? members
var classMembers = type.flatMap { classMembersByType[$0] } ?? Set<String>()
var localNames = localNames
do {
var i = index
var classOrStatic = false
outer: while let token = formatter.token(at: i) {
switch token {
case .keyword("import"):
guard let nextIndex = formatter.index(of: .identifier, after: i) else {
return // error
}
i = nextIndex
case .keyword("class"), .keyword("static"):
classOrStatic = true
case .keyword("repeat"):
guard let nextIndex = formatter.index(of: .keyword("while"), after: i) else {
return // error
}
i = nextIndex
case .keyword("if"), .keyword("while"):
guard let nextIndex = formatter.index(of: .startOfScope("{"), after: i) else {
return // error
}
i = nextIndex
continue
case .keyword("switch"):
guard let nextIndex = formatter.index(of: .startOfScope("{"), after: i),
var endIndex = formatter.index(of: .endOfScope, after: nextIndex)
else {
return // error
}
while formatter.tokens[endIndex] != .endOfScope("}") {
guard let nextIndex = formatter.index(of: .startOfScope(":"), after: endIndex),
let _endIndex = formatter.index(of: .endOfScope, after: nextIndex)
else {
return // error
}
endIndex = _endIndex
}
i = endIndex
case .keyword("var"), .keyword("let"):
i += 1
if isTypeRoot {
if classOrStatic {
formatter.processDeclaredVariables(at: &i, names: &classMembers)
classOrStatic = false
} else {
formatter.processDeclaredVariables(at: &i, names: &members)
}
} else {
formatter.processDeclaredVariables(at: &i, names: &localNames)
}
case .keyword("func"):
guard let nameToken = formatter.next(.nonSpaceOrCommentOrLinebreak, after: i) else {
break
}
if isTypeRoot {
if classOrStatic {
classMembers.insert(nameToken.unescaped())
classOrStatic = false
} else {
members.insert(nameToken.unescaped())
}
} else {
localNames.insert(nameToken.unescaped())
}
case .startOfScope("("), .startOfScope("#if"), .startOfScope(":"):
break
case .startOfScope:
classOrStatic = false
i = formatter.endOfScope(at: i) ?? (formatter.tokens.count - 1)
case .endOfScope("}"), .endOfScope("case"), .endOfScope("default"):
break outer
default:
break
}
i += 1
}
}
if let type = type {
membersByType[type] = members
classMembersByType[type] = classMembers
}
// Remove or add `self`
var scopeStack = [Token]()
var lastKeyword = ""
var lastKeywordIndex = 0
var classOrStatic = false
while let token = formatter.token(at: index) {
switch token {
case .keyword("is"), .keyword("as"), .keyword("try"), .keyword("await"):
break
case .keyword("init"), .keyword("subscript"),
.keyword("func") where lastKeyword != "import":
lastKeyword = ""
if classOrStatic {
if !isTypeRoot {
return // error
}
processFunction(at: &index, localNames: localNames, members: classMembers,
typeStack: &typeStack, membersByType: &membersByType,
classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved)
classOrStatic = false
} else {
processFunction(at: &index, localNames: localNames, members: members,
typeStack: &typeStack, membersByType: &membersByType,
classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved)
}
assert(formatter.token(at: index) != .endOfScope("}"))
continue
case .keyword("static"):
classOrStatic = true
case .keyword("class"):
if formatter.next(.nonSpaceOrCommentOrLinebreak, after: index)?.isIdentifier == true {
fallthrough
}
if formatter.last(.nonSpaceOrCommentOrLinebreak, before: index) != .delimiter(":") {
classOrStatic = true
}
case .keyword("extension"), .keyword("struct"), .keyword("enum"):
guard formatter.last(.nonSpaceOrCommentOrLinebreak, before: index) != .keyword("import"),
let scopeStart = formatter.index(of: .startOfScope("{"), after: index) else { return }
guard let nameToken = formatter.next(.identifier, after: index),
case let .identifier(name) = nameToken
else {
return // error
}
// TODO: Add usingDynamicLookup logic from the main rule
index = scopeStart + 1
typeStack.append(name)
processBody(at: &index, localNames: ["init"], members: [], typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: true, isInit: false)
typeStack.removeLast()
case .keyword("var"), .keyword("let"):
index += 1
switch lastKeyword {
case "lazy" where formatter.options.swiftVersion < "4":
loop: while let nextIndex =
formatter.index(of: .nonSpaceOrCommentOrLinebreak, after: index)
{
switch formatter.tokens[nextIndex] {
case .keyword("is"), .keyword("as"), .keyword("try"), .keyword("await"):
break
case .keyword, .startOfScope("{"):
break loop
default:
break
}
index = nextIndex
}
lastKeyword = ""
case "if", "while", "guard":
assert(!isTypeRoot)
// Guard is included because it's an error to reference guard vars in body
var scopedNames = localNames
formatter.processDeclaredVariables(at: &index, names: &scopedNames)
guard let startIndex = formatter.index(of: .startOfScope("{"), after: index) else {
return // error
}
index = startIndex + 1
processBody(at: &index, localNames: scopedNames, members: members, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: isInit)
lastKeyword = ""
default:
lastKeyword = token.string
}
classOrStatic = false
case .keyword("where") where lastKeyword == "in":
lastKeyword = ""
var localNames = localNames
guard let keywordIndex = formatter.index(of: .keyword, before: index),
let prevKeywordIndex = formatter.index(of: .keyword, before: keywordIndex),
let prevKeywordToken = formatter.token(at: prevKeywordIndex),
case .keyword("for") = prevKeywordToken else { return }
for token in formatter.tokens[prevKeywordIndex + 1 ..< keywordIndex] {
if case let .identifier(name) = token, name != "_" {
localNames.insert(token.unescaped())
}
}
index += 1
processBody(at: &index, localNames: localNames, members: members, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: isInit)
continue
case .keyword("while") where lastKeyword == "repeat":
lastKeyword = ""
case let .keyword(name):
lastKeyword = name
lastKeywordIndex = index
case .startOfScope("//"), .startOfScope("/*"):
if case let .commentBody(comment)? = formatter.next(.nonSpace, after: index) {
formatter.processCommentBody(comment, at: index)
if token == .startOfScope("//") {
formatter.processLinebreak()
}
}
index = formatter.endOfScope(at: index) ?? (formatter.tokens.count - 1)
case .startOfScope("("):
if case let .identifier(fn)? = formatter.last(.nonSpaceOrCommentOrLinebreak, before: index),
selfRequired.contains(fn) || fn == "expect"
{
index = formatter.index(of: .endOfScope(")"), after: index) ?? index
break
}
fallthrough
case .startOfScope where token.isStringDelimiter, .startOfScope("#if"):
scopeStack.append(token)
case .startOfScope(":"):
lastKeyword = ""
case .startOfScope("{") where lastKeyword == "catch":
lastKeyword = ""
var localNames = localNames
localNames.insert("error") // Implicit error argument
index += 1
processBody(at: &index, localNames: localNames, members: members, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: isInit)
continue
case .startOfScope("{") where lastKeyword == "in":
lastKeyword = ""
var localNames = localNames
guard let keywordIndex = formatter.index(of: .keyword, before: index),
let prevKeywordIndex = formatter.index(of: .keyword, before: keywordIndex),
let prevKeywordToken = formatter.token(at: prevKeywordIndex),
case .keyword("for") = prevKeywordToken else { return }
for token in formatter.tokens[prevKeywordIndex + 1 ..< keywordIndex] {
if case let .identifier(name) = token, name != "_" {
localNames.insert(token.unescaped())
}
}
index += 1
if classOrStatic {
assert(isTypeRoot)
processBody(at: &index, localNames: localNames, members: classMembers, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: false)
classOrStatic = false
} else {
processBody(at: &index, localNames: localNames, members: members, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: isInit)
}
continue
case .startOfScope("{") where isWhereClause:
return
case .startOfScope("{") where lastKeyword == "switch":
lastKeyword = ""
index += 1
loop: while let token = formatter.token(at: index) {
index += 1
switch token {
case .endOfScope("case"), .endOfScope("default"):
let localNames = localNames
processBody(at: &index, localNames: localNames, members: members, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: isInit)
index -= 1
case .endOfScope("}"):
break loop
default:
break
}
}
case .startOfScope("{") where ["for", "where", "if", "else", "while", "do"].contains(lastKeyword):
if let scopeIndex = formatter.index(of: .startOfScope, before: index), scopeIndex > lastKeywordIndex {
index = formatter.endOfScope(at: index) ?? (formatter.tokens.count - 1)
break
}
lastKeyword = ""
fallthrough
case .startOfScope("{") where lastKeyword == "repeat":
index += 1
processBody(at: &index, localNames: localNames, members: members, typeStack: &typeStack,
membersByType: &membersByType, classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved,
isTypeRoot: false, isInit: isInit)
continue
case .startOfScope("{") where lastKeyword == "var":
lastKeyword = ""
if formatter.isStartOfClosure(at: index, in: scopeStack.last) {
fallthrough
}
var prevIndex = index - 1
var name: String?
while let token = formatter.token(at: prevIndex), token != .keyword("var") {
if token.isLvalue, let nextToken = formatter.nextToken(after: prevIndex, where: {
!$0.isSpaceOrCommentOrLinebreak && !$0.isStartOfScope
}), nextToken.isRvalue, !nextToken.isOperator(".") {
// It's a closure
fallthrough
}
if case let .identifier(_name) = token {
// Is the declared variable
name = _name
}
prevIndex -= 1
}
if let name = name {
processAccessors(["get", "set", "willSet", "didSet"], for: name,
at: &index, localNames: localNames, members: members,
typeStack: &typeStack, membersByType: &membersByType,
classMembersByType: &classMembersByType,
removed: &removed, unremoved: &unremoved,
initRemoved: &initRemoved, initUnremoved: &initUnremoved)
}
continue
case .startOfScope:
index = formatter.endOfScope(at: index) ?? (formatter.tokens.count - 1)
case .identifier("self"):
guard !isTypeRoot, !localNames.contains("self"),
let dotIndex = formatter.index(of: .nonSpaceOrLinebreak, after: index, if: {
$0 == .operator(".", .infix)
}),
let nextIndex = formatter.index(of: .nonSpaceOrLinebreak, after: dotIndex),
let name = formatter.token(at: nextIndex)?.unescaped(),
!localNames.contains(name), !selfRequired.contains(name),
!_FormatRules.globalSwiftFunctions.contains(name)
else {
break
}
if isInit {
if formatter.next(.nonSpaceOrCommentOrLinebreak, after: nextIndex) == .operator("=", .infix) {
initUnremoved += 1
} else if let scopeEnd = formatter.index(of: .endOfScope(")"), after: nextIndex),
formatter.next(.nonSpaceOrCommentOrLinebreak, after: scopeEnd) == .operator("=", .infix)
{
initUnremoved += 1
} else {
unremoved += 1
}