forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiscouragedOptionalCollectionRule.swift
More file actions
174 lines (151 loc) · 6.86 KB
/
Copy pathDiscouragedOptionalCollectionRule.swift
File metadata and controls
174 lines (151 loc) · 6.86 KB
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
//
// DiscouragedOptinalCollection.swift
// SwiftLint
//
// Created by Ornithologist Coder on 1/10/18.
// Copyright © 2018 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct DiscouragedOptionalCollectionRule: ASTRule, OptInRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "discouraged_optional_collection",
name: "Discouraged Optional Collection",
description: "Prefer empty collection over optional collection.",
kind: .idiomatic,
nonTriggeringExamples: DiscouragedOptionalCollectionExamples.nonTriggeringExamples,
triggeringExamples: DiscouragedOptionalCollectionExamples.triggeringExamples
)
public func validate(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
let offsets = variableViolations(file: file, kind: kind, dictionary: dictionary) +
functionViolations(file: file, kind: kind, dictionary: dictionary)
return offsets.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: $0))
}
}
// MARK: - Private
private func variableViolations(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [Int] {
guard
SwiftDeclarationKind.variableKinds.contains(kind),
let offset = dictionary.offset,
let typeName = dictionary.typeName else { return [] }
return typeName.optionalCollectionRanges().map { _ in offset }
}
private func functionViolations(file: File,
kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [Int] {
guard
SwiftDeclarationKind.functionKinds.contains(kind),
let nameOffset = dictionary.nameOffset,
let nameLength = dictionary.nameLength,
let length = dictionary.length,
let offset = dictionary.offset,
case let start = nameOffset + nameLength,
case let end = dictionary.bodyOffset ?? offset + length,
case let contents = file.contents.bridge(),
let range = contents.byteRangeToNSRange(start: start, length: end - start),
let match = file.match(pattern: "->\\s*(.*?)\\{", excludingSyntaxKinds: excludingKinds, range: range).first
else { return [] }
return contents.substring(with: match).optionalCollectionRanges().map { _ in nameOffset }
}
private let excludingKinds = SyntaxKind.allKinds.subtracting([.typeidentifier])
}
private extension String {
/// Ranges of optional collections within the bounds of the string.
///
/// Example: [String: [Int]?]
///
/// [ S t r i n g : [ I n t ] ? ]
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/// ^ ^
/// = [9, 14]
/// = [9, 15), mathematical interval, w/ lower and upper bounds.
///
/// Example: [String: [Int]?]?
///
/// [ S t r i n g : [ I n t ] ? ] ?
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/// ^ ^ ^ ^
/// = [0, 16], [9, 14]
/// = [0, 17), [9, 15), mathematical interval, w/ lower and upper bounds.
///
/// Example: var x = Set<Int>?
///
/// v a r x = S e t < I n t > ?
/// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/// ^ ^
/// = [8, 16]
/// = [8, 17), mathematical interval, w/ lower and upper bounds.
///
/// - Returns: An array of ranges.
func optionalCollectionRanges() -> [Range<String.Index>] {
let squareBrackets = balancedRanges(from: "[", to: "]").flatMap { range -> Range<String.Index>? in
guard
range.upperBound < endIndex,
let finalIndex = index(range.upperBound, offsetBy: 1, limitedBy: endIndex),
self[range.upperBound] == "?" else { return nil }
return Range(range.lowerBound..<finalIndex)
}
let angleBrackets = balancedRanges(from: "<", to: ">").flatMap { range -> Range<String.Index>? in
guard
range.upperBound < endIndex,
let initialIndex = index(range.lowerBound, offsetBy: -3, limitedBy: startIndex),
let finalIndex = index(range.upperBound, offsetBy: 1, limitedBy: endIndex),
self[initialIndex..<range.lowerBound] == "Set",
self[range.upperBound] == "?" else { return nil }
return Range(initialIndex..<finalIndex)
}
return squareBrackets + angleBrackets
}
/// Indices of character within the bounds of the string.
///
/// Example:
/// a m a n h a
/// 0 1 2 3 4 5
/// ^ ^ ^
/// = [0, 2, 5]
///
/// - Parameter character: The character to look for.
/// - Returns: Array of indices.
private func indices(of character: Character) -> [String.Index] {
return indices.flatMap { self[$0] == character ? $0 : nil }
}
/// Ranges of balanced substrings.
///
/// Example: ((1+2)*(3+4))
///
/// ( ( 1 + 2 ) * ( 3 + 4 ) )
/// 0 1 2 3 4 5 6 7 8 9 10 11 12
/// ^ ^ ^ ^ ^ ^
/// = [0, 12], [1, 5], [7, 11]
/// = [0, 13), [1, 6), [7, 12), mathematical interval, w/ lower and upper bounds.
///
/// - Parameters:
/// - prefix: The prefix to look for.
/// - suffix: The suffix to look for.
/// - Returns: Array of ranges of balanced substrings
private func balancedRanges(from prefix: Character, to suffix: Character) -> [Range<String.Index>] {
return indices(of: prefix).flatMap { prefixIndex in
var pairCount = 0
var currentIndex = prefixIndex
var foundCharacter = false
while currentIndex < endIndex {
let character = self[currentIndex]
currentIndex = index(after: currentIndex)
if character == prefix { pairCount += 1 }
if character == suffix { pairCount -= 1 }
if pairCount != 0 { foundCharacter = true }
if pairCount == 0 && foundCharacter { break }
}
return pairCount == 0 && foundCharacter ? Range(prefixIndex..<currentIndex) : nil
}
}
}