-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
IdentifierNameRule.swift
256 lines (229 loc) · 9.34 KB
/
IdentifierNameRule.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
import Foundation
import SwiftLintCore
import SwiftSyntax
@SwiftSyntaxRule
struct IdentifierNameRule: Rule {
var configuration = IdentifierNameConfiguration()
static let description = RuleDescription(
identifier: "identifier_name",
name: "Identifier Name",
description: "Identifier names should only contain alphanumeric characters and " +
"start with a lowercase character or should only contain capital letters. " +
"In an exception to the above, variable names may start with a capital letter " +
"when they are declared as static. Variable names should not be too " +
"long or too short.",
kind: .style,
nonTriggeringExamples: IdentifierNameRuleExamples.nonTriggeringExamples,
triggeringExamples: IdentifierNameRuleExamples.triggeringExamples,
deprecatedAliases: ["variable_name"]
)
}
private extension IdentifierNameRule {
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
private lazy var nameConfiguration = configuration.nameConfiguration
override func visitPost(_ node: AccessorParametersSyntax) {
collectViolations(from: .variable(name: node.name.text, isStatic: false, isPrivate: false), on: node.name)
}
override func visitPost(_ node: ClosureParameterSyntax) {
if node.modifiers.contains(keyword: .override) {
return
}
let name = node.secondName ?? node.firstName
collectViolations(
from: .variable(name: name.text.leadingDollarStripped, isStatic: false, isPrivate: false),
on: name
)
}
override func visitPost(_ node: ClosureShorthandParameterSyntax) {
collectViolations(
from: .variable(name: node.name.text.leadingDollarStripped, isStatic: false, isPrivate: false),
on: node.name
)
}
override func visitPost(_ node: EnumCaseElementSyntax) {
collectViolations(from: .enumElement(name: node.name.text), on: node.name)
}
override func visitPost(_ node: EnumCaseParameterSyntax) {
if let name = node.secondName ?? node.firstName {
collectViolations(from: .variable(name: name.text, isStatic: false, isPrivate: false), on: name)
}
}
override func visitPost(_ node: FunctionDeclSyntax) {
let name = node.name.text
if node.modifiers.contains(keyword: .override) || isOperator(name: name) {
return
}
let type = NamedDeclType.function(
name: name,
resolvedName: node.resolvedName,
isPrivate: node.modifiers.containsPrivateOrFileprivate()
)
collectViolations(from: type, on: node.name)
}
override func visitPost(_ node: FunctionParameterSyntax) {
if node.modifiers.contains(keyword: .override) {
return
}
let name = (node.secondName ?? node.firstName)
collectViolations(
from: .variable(name: name.text, isStatic: false, isPrivate: false),
on: name
)
}
override func visitPost(_ node: IdentifierPatternSyntax) {
let varDecl = node.enclosingVarDecl
if varDecl?.modifiers.contains(keyword: .override) ?? false {
return
}
let type = NamedDeclType.variable(
name: node.identifier.text,
isStatic: varDecl?.modifiers.contains(keyword: .static) ?? false,
isPrivate: varDecl?.modifiers.containsPrivateOrFileprivate() ?? false
)
collectViolations(from: type, on: node.identifier)
}
private func collectViolations(from type: NamedDeclType, on token: TokenSyntax) {
if let violation = violates(type) {
violations.append(ReasonedRuleViolation(
position: token.positionAfterSkippingLeadingTrivia,
reason: violation.reason,
severity: violation.severity
))
}
}
private func violates(_ type: NamedDeclType) -> (reason: String, severity: ViolationSeverity)? {
guard !nameConfiguration.shouldExclude(name: type.name), type.name != "_",
let firstCharacter = type.name.first else {
return nil
}
if case .function = type {
// Do not perform additional checks.
} else {
if !nameConfiguration.containsOnlyAllowedCharacters(name: type.name) {
let reason = """
\(type) should only contain alphanumeric and other \
allowed characters
"""
return (reason, nameConfiguration.unallowedSymbolsSeverity.severity)
}
if let severity = nameConfiguration.severity(forLength: type.name.count) {
let reason = """
\(type) should be between \
\(nameConfiguration.minLengthThreshold) and \
\(nameConfiguration.maxLengthThreshold) characters long
"""
return (reason, severity)
}
}
if nameConfiguration.allowedSymbols.contains(String(firstCharacter)) {
return nil
}
if let caseCheckSeverity = nameConfiguration.validatesStartWithLowercase.severity,
!type.isStatic, type.name.isViolatingCase, !isOperator(name: type.name) {
let reason = "\(type) should start with a lowercase character"
return (reason, caseCheckSeverity)
}
return nil
}
private func isOperator(name: String) -> Bool {
configuration.additionalOperators.contains { name.hasPrefix($0) }
}
}
}
private extension DeclModifierListSyntax {
var staticOrClassModifier: DeclModifierSyntax? {
first { ["static", "class"].contains($0.name.text) }
}
}
private extension IdentifierPatternSyntax {
var enclosingVarDecl: VariableDeclSyntax? {
let identifierDecl =
parent?.as(PatternBindingSyntax.self)?
.parent?.as(PatternBindingListSyntax.self)?
.parent?.as(VariableDeclSyntax.self)
if identifierDecl != nil {
return identifierDecl
}
return
parent?.as(TuplePatternElementSyntax.self)?
.parent?.as(TuplePatternElementListSyntax.self)?
.parent?.as(TuplePatternSyntax.self)?
.parent?.as(PatternBindingSyntax.self)?
.parent?.as(PatternBindingListSyntax.self)?
.parent?.as(VariableDeclSyntax.self)
}
}
private extension VariableDeclSyntax {
var allDeclaredNames: [String] {
bindings
.map(\.pattern)
.flatMap { pattern -> [String] in
if let id = pattern.as(IdentifierPatternSyntax.self) {
[id.identifier.text]
} else if let tuple = pattern.as(TuplePatternSyntax.self) {
tuple.elements.compactMap {
$0.pattern.as(IdentifierPatternSyntax.self)?.identifier.text
}
} else {
[]
}
}
}
}
private enum NamedDeclType: CustomStringConvertible {
case function(name: String, resolvedName: String, isPrivate: Bool)
case enumElement(name: String)
case variable(name: String, isStatic: Bool, isPrivate: Bool)
var description: String {
switch self {
case let .function(_, resolvedName, _): "Function name '\(resolvedName)'"
case let .enumElement(name): "Enum element name '\(name)'"
case let .variable(name, _, _): "Variable name '\(name)'"
}
}
var isStatic: Bool {
switch self {
case .function, .enumElement: false
case let .variable(_, isStatic, _): isStatic
}
}
var isPrivate: Bool {
switch self {
case let .function(_, _, isPrivate): isPrivate
case .enumElement: false
case let .variable(_, _, isPrivate): isPrivate
}
}
var name: String {
let name = switch self {
case let .function(name, _, _): name
case let .enumElement(name): name
case let .variable(name, _, _): name
}
return name
.trimmingCharacters(in: CharacterSet(charactersIn: "`"))
.strippingLeadingUnderscore(if: isPrivate)
}
}
private extension String {
var isViolatingCase: Bool {
let firstCharacter = String(self[startIndex])
guard firstCharacter.isUppercase() else {
return false
}
guard count > 1 else {
return true
}
let secondCharacter = String(self[index(after: startIndex)])
return secondCharacter.isLowercase()
}
func strippingLeadingUnderscore(if isPrivate: Bool) -> Self {
isPrivate && first == "_" ? allButFirstCharacter : self
}
var leadingDollarStripped: Self {
first == "$" ? allButFirstCharacter : self
}
private var allButFirstCharacter: String {
String(self[index(after: startIndex)...])
}
}