forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OperatorFunctionWhitespaceRule.swift
52 lines (46 loc) · 2.16 KB
/
OperatorFunctionWhitespaceRule.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
//
// OperatorWhitespaceRule.swift
// SwiftLint
//
// Created by Akira Hirakawa on 8/6/15.
// Copyright © 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct OperatorFunctionWhitespaceRule: ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "operator_whitespace",
name: "Operator Function Whitespace",
description: "Operators should be surrounded by a single whitespace when defining them.",
kind: .style,
nonTriggeringExamples: [
"func <| (lhs: Int, rhs: Int) -> Int {}\n",
"func <|< <A>(lhs: A, rhs: A) -> A {}\n",
"func abc(lhs: Int, rhs: Int) -> Int {}\n"
],
triggeringExamples: [
"↓func <|(lhs: Int, rhs: Int) -> Int {}\n", // no spaces after
"↓func <|<<A>(lhs: A, rhs: A) -> A {}\n", // no spaces after
"↓func <| (lhs: Int, rhs: Int) -> Int {}\n", // 2 spaces after
"↓func <|< <A>(lhs: A, rhs: A) -> A {}\n", // 2 spaces after
"↓func <| (lhs: Int, rhs: Int) -> Int {}\n", // 2 spaces before
"↓func <|< <A>(lhs: A, rhs: A) -> A {}\n" // 2 spaces before
]
)
public func validate(file: File) -> [StyleViolation] {
let escapedOperators = ["/", "=", "-", "+", "!", "*", "|", "^", "~", "?", "."]
.map({ "\\\($0)" }).joined()
let operators = "\(escapedOperators)%<>&"
let zeroOrManySpaces = "(\\s{0}|\\s{2,})"
let pattern1 = "func\\s+[\(operators)]+\(zeroOrManySpaces)(<[A-Z]+>)?\\("
let pattern2 = "func\(zeroOrManySpaces)[\(operators)]+\\s+(<[A-Z]+>)?\\("
return file.match(pattern: "(\(pattern1)|\(pattern2))").filter { _, syntaxKinds in
return syntaxKinds.first == .keyword
}.map { range, _ in
return StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: range.location))
}
}
}