Skip to content

Commit c269c65

Browse files
committed
Add a syntactic "Add Codable structs from JSON" code action
Add a syntactic action that takes JSON pasted into a Swift file or placed in a string literal, then turns it into a set of Codable structs that can represent the JSON. Our typical example starts like this: ``` { "name": "Produce", "shelves": [ { "name": "Discount Produce", "product": { "name": "Banana", "points": 200, "description": "A banana that's perfectly ripe." } } ] } ``` and turns into this: ```swift struct JSONValue: Codable { var name: String var shelves: [Shelves] struct Shelves: Codable { var name: String var product: Product struct Product: Codable { var description: String var name: String var points: Double } } } ``` This code action can definitely be improved by doing more work in analyzing the JSON to (for example) abstract over multiple elements in an array to make fields optional (if they only show up in some members) and perhaps even identify when we really have something that's an enum. Such improvements can be done without changing the general shape of this refactor. The refactoring itself would live down in the swift-syntax package if not for its dependency on Foundation. We'll move as appropriate.
1 parent a92b68a commit c269c65

File tree

5 files changed

+693
-0
lines changed

5 files changed

+693
-0
lines changed

Sources/SourceKitLSP/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ target_sources(SourceKitLSP PRIVATE
2323
target_sources(SourceKitLSP PRIVATE
2424
Swift/AdjustPositionToStartOfIdentifier.swift
2525
Swift/CodeActions/ConvertIntegerLiteral.swift
26+
Swift/CodeActions/ConvertJSONToCodableStruct.swift
2627
Swift/CodeActions/SyntaxCodeActionProvider.swift
2728
Swift/CodeActions/SyntaxCodeActions.swift
2829
Swift/CodeActions/SyntaxRefactoringCodeActionProvider.swift
Lines changed: 316 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,316 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
import Foundation
14+
import LanguageServerProtocol
15+
import SwiftRefactor
16+
import SwiftSyntax
17+
18+
/// Convert JSON literals into corresponding Swift structs that conform to the
19+
/// `Codable` protocol.
20+
///
21+
/// ## Before
22+
///
23+
/// ```javascript
24+
/// {
25+
/// "name": "Produce",
26+
/// "shelves": [
27+
/// {
28+
/// "name": "Discount Produce",
29+
/// "product": {
30+
/// "name": "Banana",
31+
/// "points": 200,
32+
/// "description": "A banana that's perfectly ripe."
33+
/// }
34+
/// }
35+
/// ]
36+
/// }
37+
/// ```
38+
///
39+
/// ## After
40+
///
41+
/// ```swift
42+
/// struct JSONValue: Codable {
43+
/// var name: String
44+
/// var shelves: [Shelves]
45+
///
46+
/// struct Shelves: Codable {
47+
/// var name: String
48+
/// var product: Product
49+
///
50+
/// struct Product: Codable {
51+
/// var description: String
52+
/// var name: String
53+
/// var points: Double
54+
/// }
55+
/// }
56+
/// }
57+
/// ```
58+
struct ConvertJSONToCodableStruct: EditRefactoringProvider {
59+
static func textRefactor(
60+
syntax: Syntax,
61+
in context: Void
62+
) -> [SourceEdit] {
63+
// Dig out a syntax node that looks like it might be JSON or have JSON
64+
// in it.
65+
guard let preflight = preflightRefactoring(syntax) else {
66+
return []
67+
}
68+
69+
// Dig out the text that we think might be JSON.
70+
let text: String
71+
switch preflight {
72+
case let .closure(closure):
73+
text = closure.trimmedDescription
74+
case let .tail(closure, unexpected):
75+
text = closure.trimmedDescription + unexpected.description
76+
case .stringLiteral(_, let literalText):
77+
text = literalText
78+
}
79+
80+
// Try to process this as JSON.
81+
guard
82+
let object = try? JSONSerialization.jsonObject(with: text.data(using: .utf8)!),
83+
let serial = object as? Dictionary<String, Any>
84+
else {
85+
return []
86+
}
87+
88+
// Build the declarations from the JSON dictionary.
89+
let decls = build(from: serial)
90+
91+
// Render the change into
92+
switch preflight {
93+
case .closure(let closure):
94+
return [
95+
SourceEdit(range: closure.trimmedRange, replacement: decls.description)
96+
]
97+
case .tail(let closure, let unexpected):
98+
return [
99+
SourceEdit(range: closure.trimmedRange, replacement: decls.description),
100+
SourceEdit(range: unexpected.range, replacement: ""),
101+
]
102+
case .stringLiteral(let literal, _):
103+
return [
104+
SourceEdit(
105+
range: literal.endPosition..<literal.endPosition,
106+
replacement: "\n" + decls.description
107+
)
108+
]
109+
}
110+
}
111+
}
112+
113+
extension ConvertJSONToCodableStruct {
114+
/// The result of preflighting a syntax node to try to find potential JSON
115+
/// in it.
116+
public enum Preflight {
117+
/// A closure, which is what a JSON dictionary looks like when pasted
118+
/// into Swift.
119+
case closure(ClosureExprSyntax)
120+
121+
/// A closure at the end of a source file, which might have extra JSON.
122+
case tail(ClosureExprSyntax, UnexpectedNodesSyntax)
123+
124+
/// A string literal that may contain JSON.
125+
case stringLiteral(StringLiteralExprSyntax, String)
126+
}
127+
128+
/// Look for either a closure or a string literal that might have JSON in it.
129+
public static func preflightRefactoring(_ syntax: Syntax) -> Preflight? {
130+
// Preflight a closure.
131+
//
132+
// A blob of JSON dropped into a Swift source file will look like a
133+
// closure due to the curly braces. The internals might be a syntactic
134+
// disaster, but we don't actually care.
135+
if let closure = syntax.as(ClosureExprSyntax.self) {
136+
if let file = closure.parent?.parent?.parent?.as(SourceFileSyntax.self),
137+
let unexpected = file.unexpectedBetweenStatementsAndEndOfFileToken
138+
{
139+
return .tail(closure, unexpected)
140+
}
141+
142+
return .closure(closure)
143+
}
144+
145+
// We found a string literal; its contents might be JSON.
146+
if let stringLit = syntax.as(StringLiteralExprSyntax.self) {
147+
guard let text = stringLit.representedLiteralValue else {
148+
return nil
149+
}
150+
151+
return .stringLiteral(stringLit, text)
152+
}
153+
154+
// Look further up the syntax tree.
155+
if let parent = syntax.parent {
156+
return preflightRefactoring(parent)
157+
}
158+
159+
return nil
160+
}
161+
}
162+
163+
extension ConvertJSONToCodableStruct: SyntaxRefactoringCodeActionProvider {
164+
static var title = "Create Codable structs from JSON"
165+
}
166+
167+
extension ConvertJSONToCodableStruct {
168+
fileprivate static let indentation = 4
169+
170+
private static func build(from jsonDictionary: Dictionary<String, Any>) -> DeclSyntax {
171+
return
172+
"""
173+
\(raw: self.buildStruct(from: jsonDictionary))
174+
"""
175+
}
176+
177+
private static func buildStruct(
178+
named name: String = "JSONValue",
179+
at depth: Int = 0,
180+
from jsonDictionary: Dictionary<String, Any>
181+
) -> String {
182+
let members = self.buildStructMembers(at: depth + 1, from: jsonDictionary)
183+
return
184+
"""
185+
\(String(repeating: " ", count: depth * indentation))struct \(name): Codable {
186+
\(members.joined(separator: "\n"))
187+
\(String(repeating: " ", count: depth * indentation))}
188+
"""
189+
}
190+
191+
private static func buildStructMembers(
192+
at depth: Int,
193+
from jsonDictionary: Dictionary<String, Any>
194+
) -> [String] {
195+
var members: [String] = []
196+
197+
var uniquer: Set<String> = []
198+
var nestedTypes: [(String, Dictionary<String, Any>)] = []
199+
func addNestedType(_ name: String, object: Dictionary<String, Any>) {
200+
guard uniquer.insert(name).inserted else {
201+
return
202+
}
203+
nestedTypes.append((name, object))
204+
}
205+
206+
for key in jsonDictionary.keys.sorted() {
207+
guard let value = jsonDictionary[key] else {
208+
continue
209+
}
210+
211+
let type = self.jsonType(of: value, suggestion: key)
212+
if case let .object(name) = type, let subObject = value as? Dictionary<String, Any> {
213+
addNestedType(name, object: subObject)
214+
} else if case let .array(innerType) = type,
215+
let array = value as? [Any],
216+
let (nesting, elementType) = innerType.outermostObject
217+
{
218+
if let subObject = array.unwrap(nesting) {
219+
addNestedType(elementType, object: subObject)
220+
}
221+
}
222+
223+
let member = "\(String(repeating: " ", count: depth * indentation))var \(key): \(type.stringValue)"
224+
members.append(member)
225+
}
226+
227+
if !nestedTypes.isEmpty {
228+
members.append("")
229+
for (name, nestedType) in nestedTypes {
230+
members.append(self.buildStruct(named: name, at: depth, from: nestedType))
231+
}
232+
}
233+
return members
234+
}
235+
236+
indirect enum JSONType {
237+
case string
238+
case double
239+
case array(JSONType)
240+
case null
241+
case object(String)
242+
243+
var outermostObject: (Int, String)? {
244+
var unwraps = 1
245+
var value = self
246+
while case let .array(inner) = value {
247+
value = inner
248+
unwraps += 1
249+
}
250+
251+
if case let .object(typeName) = value {
252+
return (unwraps, typeName)
253+
} else {
254+
return nil
255+
}
256+
}
257+
258+
var stringValue: String {
259+
switch self {
260+
case .string:
261+
return "String"
262+
case .double:
263+
return "Double"
264+
case .array(let ty):
265+
return "[\(ty.stringValue)]"
266+
case .null:
267+
return "Void?"
268+
case let .object(name):
269+
return name
270+
}
271+
}
272+
}
273+
274+
private static func jsonType(of value: Any, suggestion name: String) -> JSONType {
275+
switch Swift.type(of: value) {
276+
case is NSString.Type:
277+
return .string
278+
case is NSNumber.Type:
279+
return .double
280+
case is NSArray.Type:
281+
guard let firstValue = (value as! [Any]).first else {
282+
return .array(.null)
283+
}
284+
let innerType = self.jsonType(of: firstValue, suggestion: name)
285+
return .array(innerType)
286+
case is NSNull.Type:
287+
return .null
288+
case is NSDictionary.Type:
289+
return .object(name.capitalized)
290+
default:
291+
return .string
292+
}
293+
}
294+
}
295+
296+
extension Array where Element == Any {
297+
fileprivate func unwrap(_ depth: Int) -> Dictionary<String, Any>? {
298+
var values: [Any] = self
299+
for i in 0..<depth {
300+
if values.isEmpty {
301+
return nil
302+
}
303+
304+
if i + 1 == depth {
305+
return values[0] as? Dictionary<String, Any>
306+
}
307+
308+
guard let moreValues = values[0] as? [Any] else {
309+
return nil
310+
}
311+
312+
values = moreValues
313+
}
314+
return nil
315+
}
316+
}

Sources/SourceKitLSP/Swift/CodeActions/SyntaxCodeActions.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import SwiftRefactor
1717
let allSyntaxCodeActions: [SyntaxCodeActionProvider.Type] = [
1818
AddSeparatorsToIntegerLiteral.self,
1919
ConvertIntegerLiteral.self,
20+
ConvertJSONToCodableStruct.self,
2021
FormatRawStringLiteral.self,
2122
MigrateToNewIfLetSyntax.self,
2223
OpaqueParameterToGeneric.self,

Tests/SourceKitLSPTests/CodeActionTests.swift

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,48 @@ final class CodeActionTests: XCTestCase {
292292
XCTAssertTrue(codeActions.contains(expectedCodeAction))
293293
}
294294

295+
func testJSONCodableCodeActionResult() async throws {
296+
let testClient = try await TestSourceKitLSPClient(capabilities: clientCapabilitiesWithCodeActionSupport())
297+
let uri = DocumentURI.for(.swift)
298+
let positions = testClient.openDocument(
299+
"""
300+
1️⃣{
301+
"name": "Produce",
302+
"shelves": [
303+
{
304+
"name": "Discount Produce",
305+
"product": {
306+
"name": "Banana",
307+
"points": 200,
308+
"description": "A banana that's perfectly ripe."
309+
}
310+
}
311+
]
312+
}
313+
""",
314+
uri: uri
315+
)
316+
317+
let testPosition = positions["1️⃣"]
318+
let request = CodeActionRequest(
319+
range: Range(testPosition),
320+
context: .init(),
321+
textDocument: TextDocumentIdentifier(uri)
322+
)
323+
let result = try await testClient.send(request)
324+
325+
guard case .codeActions(let codeActions) = result else {
326+
XCTFail("Expected code actions")
327+
return
328+
}
329+
330+
// Make sure we get a JSON conversion action.
331+
let codableAction = codeActions.first { action in
332+
return action.title == "Create Codable structs from JSON"
333+
}
334+
XCTAssertNotNil(codableAction)
335+
}
336+
295337
func testSemanticRefactorRangeCodeActionResult() async throws {
296338
let testClient = try await TestSourceKitLSPClient(capabilities: clientCapabilitiesWithCodeActionSupport())
297339
let uri = DocumentURI.for(.swift)

0 commit comments

Comments
 (0)