@@ -12,6 +12,56 @@ import SwiftSyntax
12
12
/// Format: Redundant labels in case patterns are removed.
13
13
///
14
14
/// - SeeAlso: https://google.github.io/swift#pattern-matching
15
- public final class NoLablesInCasePatterns : SyntaxFormatRule {
15
+ public final class NoLabelsInCasePatterns : SyntaxFormatRule {
16
+ public override func visit( _ node: SwitchCaseLabelSyntax ) -> Syntax {
16
17
18
+ var newCaseItems : [ CaseItemSyntax ] = [ ]
19
+ for item in node. caseItems {
20
+ guard let expPat = item. pattern as? ExpressionPatternSyntax else {
21
+ newCaseItems. append ( item)
22
+ continue
23
+ }
24
+ guard let funcCall = expPat. expression as? FunctionCallExprSyntax else {
25
+ newCaseItems. append ( item)
26
+ continue
27
+ }
28
+
29
+ // Search function call argument list for violations
30
+ var newArgs : [ FunctionCallArgumentSyntax ] = [ ]
31
+ for argument in funcCall. argumentList {
32
+ guard let label = argument. label else {
33
+ newArgs. append ( argument)
34
+ continue
35
+ }
36
+ guard let unresolvedPat = argument. expression as? UnresolvedPatternExprSyntax ,
37
+ let valueBinding = unresolvedPat. pattern as? ValueBindingPatternSyntax else {
38
+ newArgs. append ( argument)
39
+ continue
40
+ }
41
+
42
+ // Remove label if it's the same as the value identifier
43
+ let name = valueBinding. valuePattern. description. trimmingCharacters ( in: . whitespaces)
44
+ guard name == label. text else {
45
+ newArgs. append ( argument)
46
+ continue
47
+ }
48
+ diagnose ( . removeRedundantLabel( name: name) , on: label)
49
+ newArgs. append ( argument. withLabel ( nil ) . withColon ( nil ) )
50
+ }
51
+
52
+ let newArgList = SyntaxFactory . makeFunctionCallArgumentList ( newArgs)
53
+ let newFuncCall = funcCall. withArgumentList ( newArgList)
54
+ let newExpPat = expPat. withExpression ( newFuncCall)
55
+ let newItem = item. withPattern ( newExpPat)
56
+ newCaseItems. append ( newItem)
57
+ }
58
+ let newCaseItemList = SyntaxFactory . makeCaseItemList ( newCaseItems)
59
+ return node. withCaseItems ( newCaseItemList)
60
+ }
61
+ }
62
+
63
+ extension Diagnostic . Message {
64
+ static func removeRedundantLabel( name: String ) -> Diagnostic . Message {
65
+ return . init( . warning, " remove \( name) label from case argument " )
66
+ }
17
67
}
0 commit comments