-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
UnusedImportRule.swift
366 lines (329 loc) · 12 KB
/
UnusedImportRule.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
import Foundation
import SourceKittenFramework
public struct UnusedImportRule: CorrectableRule, ConfigurationProviderRule, AnalyzerRule, AutomaticTestableRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "unused_import",
name: "Unused Import",
description: "All imported modules should be required to make the file compile.",
kind: .lint,
nonTriggeringExamples: [
"""
import Dispatch
dispatchMain()
""",
"""
@testable import Dispatch
dispatchMain()
""",
"""
import Foundation
@objc
class A {}
""",
"""
import UnknownModule
func foo(error: Swift.Error) {}
""",
"""
import Foundation
import ObjectiveC
let 👨👩👧👦 = #selector(NSArray.contains(_:))
👨👩👧👦 == 👨👩👧👦
"""
],
triggeringExamples: [
"""
↓import Dispatch
struct A {
static func dispatchMain() {}
}
A.dispatchMain()
""",
"""
↓import Foundation
struct A {
static func dispatchMain() {}
}
A.dispatchMain()
↓import Dispatch
""",
"""
↓import Foundation
dispatchMain()
""",
"""
↓import Foundation
// @objc
class A {}
""",
"""
↓import Foundation
import UnknownModule
func foo(error: Swift.Error) {}
"""
],
corrections: [
"""
↓import Dispatch
struct A {
static func dispatchMain() {}
}
A.dispatchMain()
""":
"""
struct A {
static func dispatchMain() {}
}
A.dispatchMain()
""",
"""
↓import Foundation
struct A {
static func dispatchMain() {}
}
A.dispatchMain()
↓import Dispatch
""":
"""
struct A {
static func dispatchMain() {}
}
A.dispatchMain()
""",
"""
↓import Foundation
dispatchMain()
""":
"""
dispatchMain()
""",
"""
↓@testable import Foundation
import Dispatch
dispatchMain()
""":
"""
import Dispatch
dispatchMain()
""",
"""
↓import Foundation
// @objc
class A {}
""":
"""
// @objc
class A {}
"""
],
requiresFileOnDisk: true
)
public func validate(file: SwiftLintFile, compilerArguments: [String]) -> [StyleViolation] {
return violationRanges(in: file, compilerArguments: compilerArguments).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: SwiftLintFile, compilerArguments: [String]) -> [Correction] {
let violations = violationRanges(in: file, compilerArguments: compilerArguments)
let matches = file.ruleEnabled(violatingRanges: violations, for: self)
if matches.isEmpty { return [] }
var contents = file.contents.bridge()
let description = type(of: self).description
var corrections = [Correction]()
for range in matches.reversed() {
contents = contents.replacingCharacters(in: range, with: "").bridge()
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents.bridge())
return corrections
}
private func violationRanges(in file: SwiftLintFile, compilerArguments: [String]) -> [NSRange] {
guard !compilerArguments.isEmpty else {
queuedPrintError("""
Attempted to lint file at path '\(file.path ?? "...")' with the \
\(type(of: self).description.identifier) rule without any compiler arguments.
""")
return []
}
return file.unusedImports(compilerArguments: compilerArguments).map { $0.1 }
}
}
private extension SwiftLintFile {
func unusedImports(compilerArguments: [String]) -> [(String, NSRange)] {
let contentsNSString = contents.bridge()
var imports = Set<String>()
var usrFragments = Set<String>()
var nextIsModuleImport = false
let tokens = syntaxMap.tokens
for token in tokens {
guard let tokenKind = token.kind else {
continue
}
if tokenKind == .keyword, contents(for: token) == "import" {
nextIsModuleImport = true
continue
}
if syntaxKindsToSkip.contains(tokenKind) {
continue
}
let cursorInfoRequest = Request.cursorInfo(file: path!, offset: Int64(token.offset),
arguments: compilerArguments)
guard let cursorInfo = (try? cursorInfoRequest.sendIfNotDisabled()).map(SourceKittenDictionary.init) else {
queuedPrintError("Could not get cursor info")
continue
}
if nextIsModuleImport {
if let importedModule = cursorInfo.moduleName,
cursorInfo.kind == "source.lang.swift.ref.module" {
imports.insert(importedModule)
nextIsModuleImport = false
continue
} else {
nextIsModuleImport = false
}
}
appendUsedImports(cursorInfo: cursorInfo, usrFragments: &usrFragments)
}
// Always disallow 'import Swift' because it's available without importing.
usrFragments.remove("Swift")
var unusedImports = imports.subtracting(usrFragments)
// Certain Swift attributes requires importing Foundation.
if unusedImports.contains("Foundation") && containsAttributesRequiringFoundation() {
unusedImports.remove("Foundation")
}
if !unusedImports.isEmpty {
unusedImports.subtract(
operatorImports(
arguments: compilerArguments,
processedTokenOffsets: Set(tokens.map { $0.offset })
)
)
}
return rangedAndSortedUnusedImports(of: Array(unusedImports), contents: contentsNSString)
}
func rangedAndSortedUnusedImports(of unusedImports: [String], contents: NSString) -> [(String, NSRange)] {
return unusedImports
.map { module in
let testableImportRange = contents.range(of: "@testable import \(module)\n")
if testableImportRange.location != NSNotFound {
return (module, testableImportRange)
}
return (module, contents.range(of: "import \(module)\n"))
}
.sorted(by: { $0.1.location < $1.1.location })
}
// Operators are omitted in the editor.open request and thus have to be looked up by the indexsource request
func operatorImports(arguments: [String], processedTokenOffsets: Set<Int>) -> Set<String> {
guard let index = (try? Request.index(file: path!, arguments: arguments).sendIfNotDisabled())
.map(SourceKittenDictionary.init) else {
queuedPrintError("Could not get index")
return []
}
let operatorEntities = flatEntities(entity: index).filter { mightBeOperator(kind: $0.kind) }
let offsetPerLine = self.offsetPerLine()
var imports = Set<String>()
for entity in operatorEntities {
if
let line = entity.line,
let column = entity.column,
let lineOffset = offsetPerLine[Int(line) - 1] {
let offset = lineOffset + column - 1
// Filter already processed tokens such as static methods that are not operators
guard !processedTokenOffsets.contains(Int(offset)) else { continue }
let cursorInfoRequest = Request.cursorInfo(file: path!, offset: offset, arguments: arguments)
guard let cursorInfo = (try? cursorInfoRequest.sendIfNotDisabled())
.map(SourceKittenDictionary.init) else {
queuedPrintError("Could not get cursor info")
continue
}
appendUsedImports(cursorInfo: cursorInfo, usrFragments: &imports)
}
}
return imports
}
func flatEntities(entity: SourceKittenDictionary) -> [SourceKittenDictionary] {
let entities = entity.entities
if entities.isEmpty {
return [entity]
} else {
return [entity] + entities.flatMap { flatEntities(entity: $0) }
}
}
func offsetPerLine() -> [Int: Int64] {
return Dictionary(
uniqueKeysWithValues: contents.bridge()
.components(separatedBy: "\n")
.map { Int64($0.bridge().lengthOfBytes(using: .utf8)) }
.reduce(into: [0]) { result, length in
let newLineCharacterLength = Int64(1)
let lineLength = length + newLineCharacterLength
result.append(contentsOf: [(result.last ?? 0) + lineLength])
}
.enumerated()
.map { ($0.offset, $0.element) }
)
}
// Operators that are a part of some body are reported as method.static
func mightBeOperator(kind: String?) -> Bool {
guard let kind = kind else { return false }
return [
"source.lang.swift.ref.function.operator",
"source.lang.swift.ref.function.method.static"
].contains { kind.hasPrefix($0) }
}
func appendUsedImports(cursorInfo: SourceKittenDictionary, usrFragments: inout Set<String>) {
if let usr = cursorInfo.moduleName {
usrFragments.formUnion(usr.split(separator: ".").map(String.init))
}
}
func containsAttributesRequiringFoundation() -> Bool {
guard contents.contains("@objc") else {
return false
}
func containsAttributesRequiringFoundation(dict: SourceKittenDictionary) -> Bool {
if !attributesRequiringFoundation.isDisjoint(with: dict.enclosedSwiftAttributes) {
return true
} else {
return dict.substructure.contains(where: containsAttributesRequiringFoundation)
}
}
return containsAttributesRequiringFoundation(dict: self.structureDictionary)
}
}
private extension SourceKittenDictionary {
/// Module name in @import expressions
var moduleName: String? {
return value["key.modulename"] as? String
}
var line: Int64? {
return value["key.line"] as? Int64
}
var column: Int64? {
return value["key.column"] as? Int64
}
}
private let syntaxKindsToSkip: Set<SyntaxKind> = [
.attributeBuiltin,
.keyword,
.number,
.docComment,
.string,
.stringInterpolationAnchor,
.attributeID,
.buildconfigKeyword,
.buildconfigID,
.commentURL,
.comment,
.docCommentField
]
private let attributesRequiringFoundation: Set<SwiftDeclarationAttributeKind> = [
.objc,
.objcName,
.objcMembers,
.objcNonLazyRealization
]