forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternMatchingKeywordsRule.swift
More file actions
84 lines (73 loc) · 2.91 KB
/
PatternMatchingKeywordsRule.swift
File metadata and controls
84 lines (73 loc) · 2.91 KB
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
//
// PatternMatchingKeywordsRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 08/23/17.
// Copyright © 2017 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct PatternMatchingKeywordsRule: ASTRule, ConfigurationProviderRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "pattern_matching_keywords",
name: "Pattern Matching Keywords",
description: "Combine multiple pattern matching bindings by moving keywords out of tuples.",
kind: .idiomatic,
nonTriggeringExamples: [
"default",
"case 1",
"case bar",
"case let (x, y)",
"case .foo(let x)",
"case let .foo(x, y)",
"case .foo(let x), .bar(let x)",
"case .foo(let x, var y)",
"case var (x, y)",
"case .foo(var x)",
"case var .foo(x, y)"
].map(wrapInSwitch),
triggeringExamples: [
"case (↓let x, ↓let y)",
"case .foo(↓let x, ↓let y)",
"case (.yamlParsing(↓let x), .yamlParsing(↓let y))",
"case (↓var x, ↓var y)",
"case .foo(↓var x, ↓var y)",
"case (.yamlParsing(↓var x), .yamlParsing(↓var y))"
].map(wrapInSwitch)
)
public func validate(file: File, kind: StatementKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .case else {
return []
}
let contents = file.contents.bridge()
return dictionary.elements.flatMap { subDictionary -> [StyleViolation] in
guard subDictionary.kind == "source.lang.swift.structure.elem.pattern",
let offset = subDictionary.offset,
let length = subDictionary.length,
let caseRange = contents.byteRangeToNSRange(start: offset, length: length) else {
return []
}
let letMatches = file.match(pattern: "\\blet\\b", with: [.keyword], range: caseRange)
let varMatches = file.match(pattern: "\\bvar\\b", with: [.keyword], range: caseRange)
if !letMatches.isEmpty && !varMatches.isEmpty {
return []
}
guard letMatches.count > 1 || varMatches.count > 1 else {
return []
}
return (letMatches + varMatches).map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
}
}
private func wrapInSwitch(_ str: String) -> String {
return "switch foo {\n" +
" \(str): break\n" +
"}"
}