forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UnusedEnumeratedRule.swift
95 lines (80 loc) · 3.19 KB
/
UnusedEnumeratedRule.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
//
// UnusedEnumeratedRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/17/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct UnusedEnumeratedRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "unused_enumerated",
name: "Unused Enumerated",
description: "When the index is not used, .enumerated() can be removed.",
nonTriggeringExamples: [
"for (idx, foo) in bar.enumerated() { }\n",
"for (_, foo) in bar.enumerated().something() { }\n",
"for (_, foo) in bar.something() { }\n",
"for foo in bar.enumerated() { }\n",
"for foo in bar { }\n",
"for (idx, _) in bar.enumerated() { }\n"
],
triggeringExamples: [
"for (↓_, foo) in bar.enumerated() { }\n",
"for (↓_, foo) in abc.bar.enumerated() { }\n",
"for (↓_, foo) in abc.something().enumerated() { }\n"
]
)
public func validate(file: File, kind: StatementKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .forEach,
isEnumeratedCall(dictionary: dictionary),
let byteRange = byteRangeForVariables(dictionary: dictionary),
let firstToken = file.syntaxMap.tokens(inByteRange: byteRange).first,
firstToken.length == 1,
SyntaxKind(rawValue: firstToken.type) == .keyword,
isUnderscore(file: file, token: firstToken) else {
return []
}
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: firstToken.offset))
]
}
private func isEnumeratedCall(dictionary: [String: SourceKitRepresentable]) -> Bool {
for subDict in dictionary.substructure {
guard let kindString = subDict.kind,
SwiftExpressionKind(rawValue: kindString) == .call,
let name = subDict.name else {
continue
}
if name.hasSuffix(".enumerated") {
return true
}
}
return false
}
private func byteRangeForVariables(dictionary: [String: SourceKitRepresentable]) -> NSRange? {
guard let elements = dictionary.elements else {
return nil
}
let expectedKind = "source.lang.swift.structure.elem.id"
for subDict in elements {
guard subDict.kind == expectedKind,
let offset = subDict.offset,
let length = subDict.length else {
continue
}
return NSRange(location: offset, length: length)
}
return nil
}
private func isUnderscore(file: File, token: SyntaxToken) -> Bool {
let contents = file.contents.bridge()
return contents.substringWithByteRange(start: token.offset, length: token.length) == "_"
}
}