-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
VerticalWhitespaceBetweenCasesRule.swift
197 lines (170 loc) · 6.23 KB
/
VerticalWhitespaceBetweenCasesRule.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
import Foundation
import SourceKittenFramework
private extension SwiftLintFile {
func violatingRanges(for pattern: String) -> [NSRange] {
return match(pattern: pattern, excludingSyntaxKinds: SyntaxKind.commentAndStringKinds)
}
}
struct VerticalWhitespaceBetweenCasesRule: Rule {
var configuration = SeverityConfiguration<Self>(.warning)
private static let nonTriggeringExamples: [Example] = [
Example("""
switch x {
case 0..<5:
print("x is low")
case 5..<10:
print("x is high")
default:
print("x is invalid")
}
"""),
Example("""
switch x {
case 0..<5:
print("x is low")
case 5..<10:
print("x is high")
default:
print("x is invalid")
}
"""),
Example("""
switch x {
case 0..<5: print("x is low")
case 5..<10: print("x is high")
default: print("x is invalid")
}
"""),
// Testing handling of trailing spaces: do not convert to """ style
Example([
"switch x { \n",
"case 1: \n",
" print(\"one\") \n",
" \n",
"default: \n",
" print(\"not one\") \n",
"} "
].joined())
]
private static let violatingToValidExamples: [Example: Example] = [
Example("""
switch x {
case 0..<5:
print("x is valid")
↓ default:
print("x is invalid")
}
"""): Example("""
switch x {
case 0..<5:
print("x is valid")
default:
print("x is invalid")
}
"""),
Example("""
switch x {
case .valid:
print("x is valid")
↓ case .invalid:
print("x is invalid")
}
"""): Example("""
switch x {
case .valid:
print("x is valid")
case .invalid:
print("x is invalid")
}
"""),
Example("""
switch x {
case .valid:
print("multiple ...")
print("... lines")
↓ case .invalid:
print("multiple ...")
print("... lines")
}
"""): Example("""
switch x {
case .valid:
print("multiple ...")
print("... lines")
case .invalid:
print("multiple ...")
print("... lines")
}
""")
]
private let pattern = "([^\\n{][ \\t]*\\n)([ \\t]*(?:case[^\\n]+|default):[ \\t]*\\n)"
private func violationRanges(in file: SwiftLintFile) -> [NSRange] {
return file.violatingRanges(for: pattern).filter {
!isFalsePositive(in: file, range: $0)
}
}
private func isFalsePositive(in file: SwiftLintFile, range: NSRange) -> Bool {
// Regex incorrectly flags blank lines that contain trailing whitespace (#2538)
let patternRegex = regex(pattern)
let substring = file.contents.substring(from: range.location, length: range.length)
guard let matchResult = patternRegex.firstMatch(in: substring, options: [], range: substring.fullNSRange),
matchResult.numberOfRanges > 1 else {
return false
}
let matchFirstRange = matchResult.range(at: 1)
let matchFirstString = substring.substring(from: matchFirstRange.location, length: matchFirstRange.length)
return matchFirstString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
extension VerticalWhitespaceBetweenCasesRule: OptInRule {
static let description = RuleDescription(
identifier: "vertical_whitespace_between_cases",
name: "Vertical Whitespace between Cases",
description: "Include a single empty line between switch cases",
kind: .style,
nonTriggeringExamples: (violatingToValidExamples.values + nonTriggeringExamples).sorted(),
triggeringExamples: Array(violatingToValidExamples.keys).sorted(),
corrections: violatingToValidExamples.removingViolationMarkers()
)
func validate(file: SwiftLintFile) -> [StyleViolation] {
let patternRegex = regex(pattern)
return violationRanges(in: file).compactMap { violationRange in
let substring = file.contents.substring(from: violationRange.location, length: violationRange.length)
guard let matchResult = patternRegex.firstMatch(in: substring, options: [],
range: substring.fullNSRange) else {
return nil
}
let violatingSubrange = matchResult.range(at: 2)
let characterOffset = violationRange.location + violatingSubrange.location
return StyleViolation(
ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: characterOffset)
)
}
}
}
extension VerticalWhitespaceBetweenCasesRule: CorrectableRule {
func correct(file: SwiftLintFile) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self)
guard violatingRanges.isNotEmpty else { return [] }
let patternRegex = regex(pattern)
let replacementTemplate = "$1\n$2"
let description = Self.description
var corrections = [Correction]()
var fileContents = file.contents
for violationRange in violatingRanges.reversed() {
fileContents = patternRegex.stringByReplacingMatches(
in: fileContents,
options: [],
range: violationRange,
withTemplate: replacementTemplate
)
let location = Location(file: file, characterOffset: violationRange.location)
let correction = Correction(ruleDescription: description, location: location)
corrections.append(correction)
}
file.write(fileContents)
return corrections
}
}