forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConditionalReturnsOnNewline.swift
61 lines (54 loc) · 2.34 KB
/
ConditionalReturnsOnNewline.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
//
// ConditionalReturnsOnNewline.swift
// SwiftLint
//
// Created by Rohan Dhaimade on 12/8/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ConditionalReturnsOnNewline: ConfigurationProviderRule, Rule, OptInRule {
public let configurationDescription = "N/A"
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "conditional_returns_on_newline",
name: "Conditional Returns on Newline",
description: "Conditional statements should always return on the next line",
nonTriggeringExamples: [
"guard true else {\n return true\n}",
"guard true,\n let x = true else {\n return true\n}",
"if true else {\n return true\n}",
"if true,\n let x = true else {\n return true\n}",
"if textField.returnKeyType == .Next {",
"if true { // return }",
"/*if true { */ return }"
],
triggeringExamples: [
"↓guard true else { return }",
"↓if true { return }",
"↓if true { break } else { return }",
"↓if true { break } else { return }",
"↓if true { return \"YES\" } else { return \"NO\" }"
]
)
public func validate(file: File) -> [StyleViolation] {
let pattern = "(guard|if)[^\n]*return"
return file.rangesAndTokens(matching: pattern).filter { _, tokens in
guard let firstToken = tokens.first, let lastToken = tokens.last,
SyntaxKind(rawValue: firstToken.type) == .keyword &&
SyntaxKind(rawValue: lastToken.type) == .keyword else {
return false
}
return ["if", "guard"].contains(content(for: firstToken, file: file)) &&
content(for: lastToken, file: file) == "return"
}.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.0.location))
}
}
private func content(for token: SyntaxToken, file: File) -> String {
return file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length) ?? ""
}
}