forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RedundantNilCoalescingRule.swift
72 lines (61 loc) · 2.6 KB
/
RedundantNilCoalescingRule.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
//
// RedundantNilCoalescingRule.swift
// SwiftLint
//
// Created by Daniel Beard on 8/24/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
private extension File {
func violatingRedundantNilCoalescingRanges() -> [NSRange] {
// {whitespace} ?? {whitespace} nil {word boundary}
return match(pattern: "\\s?\\?{2}\\s*nil\\b", with: [.keyword])
}
}
public struct RedundantNilCoalescingRule: OptInRule, CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "redundant_nil_coalescing",
name: "Redundant Nil Coalescing",
description: "nil coalescing operator is only evaluated if the lhs is nil" +
", coalescing operator with nil as rhs is redundant",
kind: .idiomatic,
nonTriggeringExamples: [
"var myVar: Int?; myVar ?? 0\n"
],
triggeringExamples: [
"var myVar: Int? = nil; myVar↓ ?? nil\n",
"var myVar: Int? = nil; myVar↓??nil\n"
],
corrections: [
"var myVar: Int? = nil; let foo = myVar↓ ?? nil\n": "var myVar: Int? = nil; let foo = myVar\n",
"var myVar: Int? = nil; let foo = myVar↓??nil\n": "var myVar: Int? = nil; let foo = myVar\n"
]
)
public func validate(file: File) -> [StyleViolation] {
return file.violatingRedundantNilCoalescingRanges().map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: file.violatingRedundantNilCoalescingRanges(), for: self)
var correctedContents = file.contents
var adjustedLocations = [Int]()
for violatingRange in violatingRanges.reversed() {
if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) {
correctedContents = correctedContents
.replacingCharacters(in: indexRange, with: "")
adjustedLocations.insert(violatingRange.location, at: 0)
}
}
file.write(correctedContents)
return adjustedLocations.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0))
}
}
}