-
Notifications
You must be signed in to change notification settings - Fork 379
Expand file tree
/
Copy pathGenerateEnumAssociatedValueAccessors.swift
More file actions
157 lines (140 loc) · 4.81 KB
/
Copy pathGenerateEnumAssociatedValueAccessors.swift
File metadata and controls
157 lines (140 loc) · 4.81 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_spi(SourceKitLSP) import LanguageServerProtocol
import SourceKitLSP
import SwiftSyntax
/// A code action that generates computed properties to extract associated
/// values and check cases for an enum.
///
/// For each case with associated values, generates:
/// - `asX: T?` — extracts the associated value, or `nil` if a different case
/// - `isX: Bool` — returns `true` if the value matches that case
///
/// Example:
/// ```swift
/// enum Value {
/// case text(String)
/// case number(Int)
/// }
/// ```
/// Generates `asText`, `isText`, `asNumber`, `isNumber` computed properties.
struct GenerateEnumAssociatedValueAccessors: SyntaxCodeActionProvider {
static func codeActions(in scope: SyntaxCodeActionScope) -> [CodeAction] {
guard let node = scope.innermostNodeContainingRange else {
return []
}
guard let enumDecl = node.findParentOfSelf(
ofType: EnumDeclSyntax.self,
stoppingIf: { _ in false }
) else {
return []
}
// Collect all cases with associated values.
let casesWithAssociatedValues = enumDecl.memberBlock.members.compactMap { member -> EnumCaseElementSyntax? in
guard let caseDecl = member.decl.as(EnumCaseDeclSyntax.self),
let element = caseDecl.elements.first,
caseDecl.elements.count == 1,
element.parameterClause != nil
else {
return nil
}
return element
}
if casesWithAssociatedValues.isEmpty {
return []
}
// Scan existing member names to avoid duplicates.
let existingMembers = Set(
enumDecl.memberBlock.members.compactMap { member -> String? in
guard let varDecl = member.decl.as(VariableDeclSyntax.self),
let binding = varDecl.bindings.first,
let pattern = binding.pattern.as(IdentifierPatternSyntax.self)
else {
return nil
}
return pattern.identifier.text
}
)
var accessors: [String] = []
for element in casesWithAssociatedValues {
let caseName = element.name.text
let capitalizedName = caseName.prefix(1).uppercased() + caseName.dropFirst()
let asName = "as\(capitalizedName)"
let isName = "is\(capitalizedName)"
guard let paramClause = element.parameterClause else { continue }
let params = Array(paramClause.parameters)
if params.count == 1 {
let typeText = params[0].type.trimmedDescription
if !existingMembers.contains(asName) {
accessors.append(
"""
var \(asName): \(typeText)? {
if case let .\(caseName)(v) = self { return v }
return nil
}
"""
)
}
} else {
let tupleTypes = params.map { $0.type.trimmedDescription }
let returnType = "(\(tupleTypes.joined(separator: ", ")))"
let bindingVars = (0..<params.count).map { "v\($0)" }
let bindingPattern = bindingVars.joined(separator: ", ")
if !existingMembers.contains(asName) {
accessors.append(
"""
var \(asName): \(returnType)? {
if case let .\(caseName)(\(bindingPattern)) = self { return (\(bindingPattern)) }
return nil
}
"""
)
}
}
if !existingMembers.contains(isName) {
accessors.append(
"""
var \(isName): Bool {
if case .\(caseName) = self { return true }
return false
}
"""
)
}
}
if accessors.isEmpty {
return []
}
// Insert before the closing brace.
let closingBrace = enumDecl.memberBlock.rightBrace
let insertPosition = scope.snapshot.position(of: closingBrace.positionAfterSkippingLeadingTrivia)
let insertionText = "\n" + accessors.joined(separator: "\n\n") + "\n"
return [
CodeAction(
title: "Generate enum associated value accessors",
kind: .refactorInline,
edit: WorkspaceEdit(
changes: [
scope.snapshot.uri: [
TextEdit(
range: Range(
uncheckedBounds: (lower: insertPosition, upper: insertPosition)
),
newText: insertionText
)
]
]
)
)
]
}
}