forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVariableNameRule.swift
83 lines (78 loc) · 3.09 KB
/
VariableNameRule.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
//
// VariableNameRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
import SwiftXPC
public struct VariableNameRule: ASTRule {
public init() {}
public static let description = RuleDescription(
identifier: "variable_name",
name: "Variable Name",
description: "Variable name should only contain alphanumeric characters and " +
"start with a a lowercase character. In an exception to the above, variable " +
"names may start with a capital letter when they are declared static and immutable.",
nonTriggeringExamples: [
"let myLet = 0",
"var myVar = 0",
"private let _myLet = 0",
"class Abc { static let MyLet = 0 }"
],
triggeringExamples: [
"let MyLet = 0",
"let _myLet = 0",
"private let myLet_ = 0"
]
)
public func validateFile(file: File,
kind: SwiftDeclarationKind,
dictionary: XPCDictionary) -> [StyleViolation] {
let variableKinds: [SwiftDeclarationKind] = [
.VarClass,
.VarGlobal,
.VarInstance,
.VarLocal,
.VarParameter,
.VarStatic
]
if !variableKinds.contains(kind) {
return []
}
guard let name = dictionary["key.name"] as? String,
let offset = (dictionary["key.offset"] as? Int64).flatMap({ Int($0) }) else {
return []
}
return name.violationsForNameAtLocation(Location(file: file, offset: offset),
dictionary: dictionary, ruleDescription: self.dynamicType.description)
}
}
extension String {
private func violationsForNameAtLocation(location: Location, dictionary: XPCDictionary,
ruleDescription: RuleDescription) -> [StyleViolation] {
var violations = [StyleViolation]()
if characters.first == "$" {
// skip block variables
return violations
}
if let kind = SwiftDeclarationKind(rawValue: (dictionary["key.kind"] as? String)!) {
let name = nameStrippingLeadingUnderscoreIfPrivate(dictionary)
let nameCharacterSet = NSCharacterSet(charactersInString: name)
let firstCharacter = name.substringToIndex(name.startIndex.successor())
if !NSCharacterSet.alphanumericCharacterSet().isSupersetOfSet(nameCharacterSet) {
violations.append(StyleViolation(ruleDescription: ruleDescription,
severity: .Error,
location: location,
reason: "Variable name should only contain alphanumeric characters: '\(name)'"))
} else if kind != SwiftDeclarationKind.VarStatic && firstCharacter.isUppercase() {
violations.append(StyleViolation(ruleDescription: ruleDescription,
severity: .Error,
location: location,
reason: "Variable name should start with a lowercase character: '\(name)'"))
}
}
return violations
}
}