-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathStaticOperatorRule.swift
More file actions
106 lines (100 loc) · 3.15 KB
/
StaticOperatorRule.swift
File metadata and controls
106 lines (100 loc) · 3.15 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import SwiftSyntax
@SwiftSyntaxRule(optIn: true)
struct StaticOperatorRule: Rule {
var configuration = SeverityConfiguration<Self>(.warning)
static let description = RuleDescription(
identifier: "static_operator",
name: "Static Operator",
description: "Operators should be declared as static functions, not free functions",
kind: .idiomatic,
nonTriggeringExamples: [
Example("""
class A: Equatable {
static func == (lhs: A, rhs: A) -> Bool {
return false
}
"""),
Example("""
class A<T>: Equatable {
static func == <T>(lhs: A<T>, rhs: A<T>) -> Bool {
return false
}
"""),
Example("""
public extension Array where Element == Rule {
static func == (lhs: Array, rhs: Array) -> Bool {
if lhs.count != rhs.count { return false }
return !zip(lhs, rhs).contains { !$0.0.isEqualTo($0.1) }
}
}
"""),
Example("""
private extension Optional where Wrapped: Comparable {
static func < (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (lhs?, rhs?):
return lhs < rhs
case (nil, _?):
return true
default:
return false
}
}
}
"""),
],
triggeringExamples: [
Example("""
↓func == (lhs: A, rhs: A) -> Bool {
return false
}
"""),
Example("""
↓func == <T>(lhs: A<T>, rhs: A<T>) -> Bool {
return false
}
"""),
Example("""
↓func == (lhs: [Rule], rhs: [Rule]) -> Bool {
if lhs.count != rhs.count { return false }
return !zip(lhs, rhs).contains { !$0.0.isEqualTo($0.1) }
}
"""),
Example("""
private ↓func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (lhs?, rhs?):
return lhs < rhs
case (nil, _?):
return true
default:
return false
}
}
"""),
]
)
}
private extension StaticOperatorRule {
final class Visitor: ViolationsSyntaxVisitor<ConfigurationType> {
override var skippableDeclarations: [any DeclSyntaxProtocol.Type] { .all }
override func visitPost(_ node: FunctionDeclSyntax) {
if node.isFreeFunction, node.isOperator {
violations.append(node.funcKeyword.positionAfterSkippingLeadingTrivia)
}
}
}
}
private extension FunctionDeclSyntax {
var isFreeFunction: Bool {
parent?.is(CodeBlockItemSyntax.self) ?? false
}
var isOperator: Bool {
switch name.tokenKind {
case .binaryOperator:
true
default:
false
}
}
}