Files
SwiftLint/Source/SwiftLintFramework/Rules/OperatorFunctionWhitespaceRule.swift
T
JP Simard b83e0991b9 Remove all file headers
The MIT license doesn't require that all files be prepended with this
licensing or copyright information. Realm confirmed that they're ok with this
change. This will enable some companies to contribute to SwiftLint and the
date & authorship information will remain accessible via git source control.
2018-05-04 13:42:02 -07:00

45 lines
2.0 KiB
Swift

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))
}
}
}