|
| 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 | +} |
0 commit comments